27
www.trinea.cn Java Annotation Trinea

Java annotation

Embed Size (px)

DESCRIPTION

Java Annotation(注解) 示例、概念及作用、分类、自定义、解析,并对几个 Android 开源库 Annotation 原理进行简析, 具体见:http://www.trinea.cn/android/java-annotation-android-open-source-analysis/

Citation preview

Page 1: Java annotation

www.trinea.cn

Java Annotation

Trinea

Page 2: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 3: Java annotation

www.trinea.cn

示例

@Overridepublic void onCreate(Bundle savedInstanceState);

@GET("/user/getFriends/{phone}")String getFriends(@Path("phone") String phone);

@InjectView(R.id.user)EditText username;

@Column(name = "Name")public String name;

Override

Retrofit

Butter Knife

ActiveAndroid

Page 4: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 5: Java annotation

www.trinea.cn

是什么——注解An annotation is a form of metadata, that can be added to Java source code.

Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.

能够添加到Java源代码的语法元数据。类、方法、变量、参数、包都可以被注解,可用来将信息元数据与程序元素进行关联

作用标记,用于告诉编译器一些信息编译时动态生成代码运行时处理逻辑

Page 6: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 7: Java annotation

www.trinea.cn

public class Person {

private int id;private String name;

public Person(int id, String name) {this.id = id;this.name = name;

}

public boolean equals(Person person) {return person.id == id;

}

public int hashCode() {return id;

}}

public static void main(String[] args) {

Set<Person> appSet = new HashSet<Person>();for (int i = 0; i < 10; i++) {

appSet.add(new Person(1, "Jim"));}System.out.println(appSet.size());

}

运行结果如何?

Page 8: Java annotation

www.trinea.cn

public class Person {

private int id;private String name;

public Person(int id, String name) {this.id = id;this.name = name;

}

@Overridepublic boolean equals(Object obj) {

return (obj instanceof Person) && (((Person)obj).id == id);}

@Overridepublic int hashCode() {

return id;}

}

Page 9: Java annotation

www.trinea.cn

分类

1、标准AnnotationOverride, Deprecated, SuppressWarnings

2、元Annotation@Retention, @Target, @Inherited, @Documented

3、自定义Annotation

Page 10: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 11: Java annotation

www.trinea.cn

自定义Annotationpublic class App {

@MethodInfo(author = “[email protected]",date = "2014/02/14",version = 2)

public String getAppName() {return "anjuke";

}}

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inheritedpublic @interface MethodInfo {

String author() default "[email protected]";

String date();

int version() default 1;}

1、注解名即为自定义注解名2、注解配置参数名为注解类的方法名

Page 12: Java annotation

www.trinea.cn

自定义Annotation1、通过@interface定义

2、方法a. 所有方法没有方法体,没有参数没有修饰符,实际只允许public & abstract修饰符,默认为public,不允许抛异常

b. 方法返回值只能是基本类型,String, Class, annotation, enumeration或者是他们的一维数组

c. 只有一个默认属性,直接用value()函数。一个属性没有表示为Mark Annotation

3、可以加default表示默认值

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inheritedpublic @interface MethodInfo {

String author() default "[email protected]";

String date();

int version() default 1;}

Page 13: Java annotation

www.trinea.cn

元Annotation@Documented 是否会保存到Javadoc文档

@Target – Anonotation可以用来修饰哪些程序元素。TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER等,未标注则表示所有

@Inherited –是否可以被继承,默认为false

@Retention –保留时间,可选值SOURCE, CLASS and RUNTIME,默认为CLASS

Page 14: Java annotation

www.trinea.cn

自定义Annotation-Retrofit

@Documented@Target(METHOD)@Retention(RUNTIME)@RestMethod("GET")public @interface GET {String value();

}

@GET("/group/{id}/users")List<User> groupList(@Path("id") int groupId);

Page 15: Java annotation

www.trinea.cn

自定义Annotation-Butter Knife

@Retention(CLASS) @Target(FIELD)public @interface InjectView {int value();

}

@InjectView(R.id.user)EditText username;

Page 16: Java annotation

www.trinea.cn

自定义Annotation-ActiveAndroid@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Column {

public enum ForeignKeyAction {SET_NULL, SET_DEFAULT, CASCADE, RESTRICT, NO_ACTION

}

public String name() default "";

public int length() default -1;

public boolean notNull() default false;

public ForeignKeyAction onUpdate() default ForeignKeyAction.NO_ACTION;

}

@Column(name = "Name")public String name;

Page 17: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 18: Java annotation

www.trinea.cn

解析Annotation——运行时解析利用getAnnotation函数得到Annotation信息

public static void main(String[] args) {

try {Class cls = Class.forName("cn.trinea.java.test.annotation.App");for (Method method : cls.getMethods()) {

MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);if (methodInfo != null) {

System.out.println("method name:" + method.getName());System.out.println("method author:" + methodInfo.author());System.out.println("method version:" + methodInfo.version());System.out.println("method date:" + methodInfo.date());

}}

} catch (ClassNotFoundException e) {e.printStackTrace();

}}

Page 19: Java annotation

www.trinea.cn

解析Annotation——运行时解析常用函数method.getAnnotation(MethodInfo.class);

method.getAnnotations();

method.isAnnotationPresent(MethodInfo.class);

其他Field Class类似

运行时解析必须要Retention为 RUNTIME

Page 20: Java annotation

www.trinea.cn

解析Annotation——编译时解析自定义AbstractProcessor

@SupportedAnnotationTypes({ "cn.trinea.java.test.annotation.MethodInfo" })public class MethodInfoProcessor extends AbstractProcessor {

@Overridepublic boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {

HashMap<String, String> map = new HashMap<String, String>();for (TypeElement te : elements) {

for (Element element : env.getElementsAnnotatedWith(te)) {MethodInfo methodInfo = element.getAnnotation(MethodInfo.class);map.put(element.getEnclosingElement().toString(), methodInfo.author());

}}return false;

}}

Page 21: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 22: Java annotation

www.trinea.cn

原理介绍-Retrofit

Page 23: Java annotation

www.trinea.cn

原理介绍-Butter Knife

Page 24: Java annotation

www.trinea.cn

原理介绍-ActiveAndroid

Page 25: Java annotation

www.trinea.cn

技巧

如何判断一个Annotation是编译时还是运行时生效??

Page 26: Java annotation

www.trinea.cn

目录一、Annotation示例

二、Annotation是什么及作用

三、Annotation分类

四、Annotation自定义

五、Annotation解析

六、几个开源库Annotation原理介绍

Page 27: Java annotation

www.trinea.cn

Q Athank you