关于java:java注解

5次阅读

共计 1132 个字符,预计需要花费 3 分钟才能阅读完成。

记录一下本人应用注解获取的过程

// 第一步:定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SimpleAnnotation {String value();
}

// 第二步:应用在办法上
public class UseAnnotation {@SimpleAnnotation(value = "testStringValue")
    public void testMethod(){}
}
// 第三步:获取哪些办法应用了
public class LogicMain {public static void main(String[] args) {
        Class<UseAnnotation> useAnnotationClass = UseAnnotation.class;
        for (Method method : useAnnotationClass.getMethods()) {SimpleAnnotation annotation = method.getAnnotation(SimpleAnnotation.class);
            if (null != annotation) {System.out.println("Method Name :" + method.getName());
                System.out.println("value :" + annotation.value());
            }
        }
    }
}

输入后果:
Method Name : testMethod
value : testStringValue


// 第一步:定义注解
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {String value() default "hello";
}

// 第二步:父类上应用,子类继承这个类
@MyAnnotation
public class Person {

}

class Student extends Person{

}

// 第三步:获取
public class TestAnnotation {public static void main(String[] args) {
        Class<Student> clazz = Student.class;
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {System.out.println(annotation);
        }
    }
}

输入后果:
@com.zcl.edu.annotation2.MyAnnotation(value=”hello”)

正文完
 0