记录一下本人应用注解获取的过程
// 第一步: 定义注解
@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”)
发表回复