第一步:
需要自己建一个注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String TYPE() default MyAnnotation.FAnno;
public static final String FAnno = "F";
public static final String SAnno = "A";
public static final String TAnno = "T";
}
第二步:
写一个测试类,加自己的注解
public class TestClass {
@MyAnnotation(TYPE = MyAnnotation.TAnno)
public void eat(){
System.out.println("我在吃饭");
}
@MyAnnotation
public void watch(){
System.out.println("我在看电视");
}
}
第三步:
写一个解析注解的类
public class ExplainMyAnnotation {
public void explain(Method method){
Annotation[] annotations = method.getAnnotations();
for (Annotation anno : annotations){
if (anno instanceof MyAnnotation){
//do sth
MyAnnotation myAnnotation = (MyAnnotation) anno;
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+myAnnotation.TYPE());
System.out.println("................................"+myAnnotation.toString());
}
}
}
}
第四步:
将带注解的类和解析注解的类关联起来
public class TestAnnotation {
public static void main(String[] args){
ExplainMyAnnotation e = new ExplainMyAnnotation();
TestClass t = new TestClass();
Method[] m = t.getClass().getMethods();
for(int i=0; i<m.length; i++){
System.out.println("第"+i+"次");
e.explain(m[i]);
}
}
}
这只是一个思路,代码写的有点垃圾,哪位大神有更好的办法,希望不吝赐教。