您的位置:首页 > 编程语言 > Java开发

怎么自己写一个像spring中的高大上的注解--思路

2017-10-30 11:16 387 查看
第一步:

需要自己建一个注解类

@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]);
}
}
}


这只是一个思路,代码写的有点垃圾,哪位大神有更好的办法,希望不吝赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐