1.首先新建一个类
@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String name(); } @Retention 表示该注解的生命周期,可选的 RetentionPolicy 参数包括RetentionPolicy.SOURCE 注解将被编译器丢弃 RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
2.public class DraweeViewAnnotation { @MyAnnotation(name = "Hello world") public void execute(){ System.out.println("method"); } }
3.如果想要获取name变量的值
需要通过反射
DraweeViewAnnotation draweeViewAnnotation=new DraweeViewAnnotation();
Class<DraweeViewAnnotation> c=DraweeViewAnnotation.class;
try {
Method method=c.getMethod("execute",new Class[]{});
if(method.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation myAnnotation=method.getAnnotation(MyAnnotation.class);
try {
//利用反射获取值
method.invoke(draweeViewAnnotation,new Object[]{});
mName = myAnnotation.name();
Toast.makeText(MainActivity.this, mName,Toast.LENGTH_SHORT).show();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}