Annotation 注解修飾
@Rentention (注解的保留時間,SOURCE(源碼)坚俗、CLASS(編譯)、RUNTIME(運行時))默認(rèn)為CLASS
@Documented:是否會保存到j(luò)avadoc文檔中
@Target:用來修飾哪些程序的元素,如 TYPE勤晚,METHOD,CONSTRUCTOR泉褐、FILED赐写、PARAMETER
自定義一個注解類 @UserGroup
@Retention(RetentionPolicy.RUNTIME)
@Target({ELementType.FIELD,ElementType.METHOD})
public @interface UserGroup{
int age();
}
然后接下來就是調(diào)用
@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);
}
}
}