No1:
标准注解:
1)@Override:覆写
2)@Deprecated:过时
3)@SuppressWarnings:取消警告
4)@SafeVarargs:申明使用了可变长度参数的方法
No2:
元注解:用来注解其他注解,从而创建新的注解
1)@Targe:注解所修饰的对象范围
2)@Inherited:注解可以被继承
3)@Documented:应该被JavaDoc工具记录
4)@Retention:保留策略
5)@Repeatable:一个注解在同一声明类型上多次使用
No3:
定义注解:
1)基本定义
public @interface Swordsman{ }
//使用
@Swordsman
public class AnnotationTest{ }
2)定义成员变量
public @interface Swordsman{
String name();
int age();
}
//使用
public class AnnotationTest{
@Swordsman(name="张无忌",age=23)
public void fighting(){
...
}
}
public @interface Swordsman{
String name() default "张无忌";
int age() default 23;
}
//使用
public class AnnotationTest{
@Swordsman
public void fighting(){ }
}
3)定义运行时注解
@Retention设定注解的保留策略
RetentionPolicy.RUNTIME:运行时动态获取注解信息
RententionPolicy.CLASS:编译时进行一些预处理操作
RententionPolicy.SOURCE:做一些检查性的操作
@Rentation(RetentationPolicy.CLASS)
public @interface Swordsman{
String name() default "张无忌";
int age() default 23;
}
No4:
运行时注解处理器
public class AnnotationProcessor{
public static void main(String[] args){
Method[] methods = AnnotationTest.class.getDeclaredMethods();
for(Method m:methods){
GET get = m.getAnnotation(GET.class);
System.out.println(get.value());
}
}
}
No5:
编译时注解处理器:
public class ClassProcessor extends AbstractProcessor{
@Override
public synchronized void init(ProcessingEnvironment processingEnv){
super.init(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv){
Messager messager = processingEnv.getMessager();
for(Element element:roundEnv.getElementsAnnotatedWith(BindView.class)){
if(element.getKind()==ElementKind.FIELD){
messager.printMessage(Diagnostic.Kind.NOTE,"printMessage:"+element.toString());
}
}
return true;
}
@Override
public Set<String> getSupportedAnnotationTypes(){
Set<String> annotations = new LinkedHashSet<String>();
annotations.add(BindView.class.getCanonicalName());
return annotations;
}
@Override
public SourceVersion getSupportedSourceVersion(){
return SourceVersion.latestSupported();
}
}
No6:
依赖注入:IoC(控制反转)容器在运行期间,动态地将某种依赖关系注入到对象中
No7:
为了解耦
public class Car{
private Engine mEngine;
public Car(){
mEngine = new PetrolEngine();
}
}
1)构造方法注入
public class Car{
private Engine mEngine;
public Car(Engine mEngine){
this.mEngine = mEngine;
}
}
2)Setter方法注入
public class Car{
private Engine mEngine;
public void set(Engine mEngine){
this.mEngine = mEngine;
}
}
3)接口注入
public interface ICar{
public void setEngine(Engine engine);
} public class Car implements ICar{
private Engine mEngine;
@Override
public void setEngine(Engine engine){
this.mEngine = engine;
}
}
No8:
No9: