Annotation 注解修饰
@Rentention (注解的保留时间,SOURCE(源码)、CLASS(编译)、RUNTIME(运行时))默认为CLASS
@Documented:是否会保存到javadoc文档中
@Target:用来修饰哪些程序的元素,如 TYPE,METHOD,CONSTRUCTOR、FILED、PARAMETER
自定义一个注解类 @UserGroup
@Retention(RetentionPolicy.RUNTIME)
@Target({ELementType.FIELD,ElementType.METHOD})
public @interface UserGroup{
int age();
}
然后接下来就是调用
@Slf4j
public class TestAnnotation {
@UserGroup(age = 20)
private int age;
public int setAge(int age){
this.age = age;
log.info("\n" + "age : " + this.age);
return this.age;
}
public static void main(String[] args)throws InstantiationException, IllegalAccessException,InvocationTargetException,NoSuchMethodException{
TestAnnotation testAnnotation = new TestAnnotation();
testAnnotation.setage();
}
public void setage() throws InstantiationException, IllegalAccessException,NoSuchMethodException, InvocationTargetException {
Class class1 = TestAnnotation.class;
for (Field field:class1.getDeclaredFields()){
if(field.isAnnotationPresent(UserGroup.class)){
UserGroup annotation = field.getAnnotation(UserGroup.class);
int age1 = annotation.age();
Method method = class1.getDeclaredMethod("setAge", int.class);
method.invoke(class1.newInstance(),age1);
}
}
}
age
网友评论