定义注解简单操作

原创
小哥 3年前 (2022-10-28) 阅读数 75 #大杂烩

1.

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldName { String value() default "wang"; }

public class User { @FieldName private String name;

private  int age;

}

public static void main(String[] args) throws Exception{ User user = new User(); Class<? extends User> c = user.getClass();

Field name = c.getDeclaredField("name");
FieldName annotation = name.getAnnotation(FieldName.class);
System.out.println(annotation.value());

}

输出:wang

2.

public class User { private String name;

private  int age;

@UserCase
public String getName() {
    return name;
}

@Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface UserCase { public String value() default "王大哥";

}

public static void main(String[] args) throws Exception{ User user = new User(); Class<? extends User> c = user.getClass();

Method getName = c.getDeclaredMethod("getName");
UserCase annotation = getName.getAnnotation(UserCase.class);
System.out.println(annotation.value());

}

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门