自定义注解简单使用

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 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 c = user.getClass();


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

}

 

 

 

 

你可能感兴趣的:(注解)