package com.test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD,ElementType.CONSTRUCTOR})
public @interface MyAnnotation {
String name();
int id() default 0;
Class<String> gid();
}
package com.test;
public class Test6 {
@MyAnnotation(name = "construct", id = 1, gid = String.class)
// 构造方法注解
public Test6() {
}
@MyAnnotation(name = "param", id = 2, gid = String.class)
// 类成员注解
private String name;
@MyAnnotation(name = "public method", id = 3, gid = String.class)
// 类方法注解
public void execute() {
}
}
package com.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ParseAnnotation {
/**
* 简单打印出UserAnnotation 类中所使用到的类注解 该方法只打印了 Constructor 类型的注解
*/
public static void parseConstructorAnnotation() {
Constructor[] constructors = Test6.class.getConstructors();
for (Constructor constructor : constructors) {
/*
* 判断Constructor中是否有指定注解类型的注解
*/
boolean hasAnnotation = constructor
.isAnnotationPresent(MyAnnotation.class);
if (hasAnnotation) {
/*
* 根据注解类型返回方法的指定类型注解
*/
MyAnnotation annotation = (MyAnnotation) constructor
.getAnnotation(MyAnnotation.class);
System.out.println("constructor = " + constructor.getName()
+ " ; id = " + annotation.id() + " ; description = "
+ annotation.name() + " ; gid = " + annotation.gid());
}
}
}
/**
* 简单打印出UserAnnotation 类中所使用到的类注解 该方法只打印了 Field 类型的注解
*/
public static void parseFieldAnnotation() {
Field[] fields = Test6.class.getDeclaredFields();
for (Field field : fields) {
/*
* 判断Field中是否有指定注解类型的注解
*/
boolean hasAnnotation = field
.isAnnotationPresent(MyAnnotation.class);
if (hasAnnotation) {
/*
* 根据注解类型返回方法的指定类型注解
*/
MyAnnotation annotation = field
.getAnnotation(MyAnnotation.class);
System.out.println("Field = " + field.getName() + " ; id = "
+ annotation.id() + " ; description = "
+ annotation.name() + " ; gid = " + annotation.gid());
}
}
}
/**
* 简单打印出UserAnnotation 类中所使用到的类注解 该方法只打印了 Method 类型的注解
*/
public static void parseMethodAnnotation() {
Method[] methods = Test6.class.getMethods();
for (Method method : methods) {
/*
* 判断Constructor中是否有指定注解类型的注解
*/
boolean hasAnnotation = method
.isAnnotationPresent(MyAnnotation.class);
if (hasAnnotation) {
/*
* 根据注解类型返回方法的指定类型注解
*/
MyAnnotation annotation = (MyAnnotation) method
.getAnnotation(MyAnnotation.class);
System.out.println("method = " + method.getName() + " ; id = "
+ annotation.id() + " ; description = "
+ annotation.name() + " ; gid = " + annotation.gid());
}
}
}
public static void main(String[] args) {
ParseAnnotation.parseConstructorAnnotation();
ParseAnnotation.parseFieldAnnotation();
parseMethodAnnotation();
}
}