两种方法
第一种
1.自定义注解类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
String value();
}
2.MainActivity
public class MainActivity extends AppCompatActivity {
private StudentBean studentBean;
private Class<? extends StudentBean> aClass;
@MyAnnotation("ZHUHUOHUO")
String mStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
自定义注解传值
MainActivity activity = new MainActivity();
Class<? extends MainActivity> aClass = activity.getClass();
Field[] fields = aClass.getDeclaredFields();
for (Field f:fields ) {
MyAnnotation annotation = f.getAnnotation(MyAnnotation.class);
if(annotation!=null){
String value = annotation.value();
Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
}
}
}
}
第二种
1.自定义注解类
@Retention(RetentionPolicy.RUNTIME)
public @interface MyNotation {
String name();
}
2.自定义注解类DraweeViewAnnotation
public class DraweeViewAnnotation {
@MyNotation(name="Hello world")
public void getValue(){ }
}
3.得到注解的值(点击事件)
TwoDraweeViewAnnotation twoDraweeViewAnnotation = new TwoDraweeViewAnnotation();
Class<TwoDraweeViewAnnotation> twoClas = TwoDraweeViewAnnotation.class;
try {
Method method = twoClas.getMethod("value", new Class[]{});
if (method.isAnnotationPresent(TwoNotation.class)){
method.getAnnotation(TwoNotation.class);
method.invoke(twoDraweeViewAnnotation,new Object[]{});
Toast.makeText(this, method.getName(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}