@Retention : RetentionPolicy. SOURCE,CLASS,RUNTIME
@Target :ElementType.TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,ANNOTATION_TYPE,PACKAGE
@Target :ElementType.TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,ANNOTATION_TYPE,PACKAGE
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface In {
/**
* 范围
*
* @return
*/
String scope();
/**
* 值
*
* @return
*/
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface UserInfo {
String name();
String age();
}
@UserInfo(name = "sefer", age = "27")
public class User {
@In(scope = "request", value = "hangzhou")
String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class GetUser {
public static void main(String[] args) {
AnnotatedElement an = User.class;
boolean isUserInfo = an.isAnnotationPresent(UserInfo.class);
if (isUserInfo) {
UserInfo userInfo = an.getAnnotation(UserInfo.class);
String name = userInfo.name();
String age = userInfo.age();
System.out.println("name: " + name);
System.out.println("age: " + age);
}
User user = new User();
Field[] fields = user.getClass().getDeclaredFields();
for (Field field : fields) {
// 重要:避免java虚拟机检查对私有成员的访问权限
field.setAccessible(true);
boolean isIn = field.isAnnotationPresent(In.class);
if (isIn) {
In in = field.getAnnotation(In.class);
System.out.println(field.getName() + "value: " + in.value());
System.out.println(field.getName() + " save scope: "
+ in.scope());
}
}
}
}