Java 文档 - 自定义注解

139 阅读2分钟

自定义注解

  • 使用@interface关键字
  • 注解放在修饰元素的上面

一个简单的注解

//定义一个简单的注解Test
public @interface Test{}

默认情况下,Annotation可以修饰任何程序元素:类、接口、方法等。

@Test
public class MyClass{
}

带成员变量的注解

以无形参的方法形式来声明Annotation的成员变量,方法名和返回值定义了成员变量名称和类型。使用default关键字设置初始值。没设置初始值的变量则使用时必须提供,有初始值的变量可以设置也可以不设置。

//定义带成员变量注解MyTag
@Rentention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag{
  //定义两个成员变量,以方法的形式定义
  String name();
  int age() default 32;
}

//使用
public class Test{
  @MyTag(name="liang")
  public void info(){}
}

再举一个自定义annotation的例子

@MethodInfo的定义

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface MethodInfo {
     String author() default "trinea@gmail.com";
     String date();
     int version() default 1;
}

MethodInfo Annotation定义部分:     

(1) 通过@interface 定义,注解名即为自定义注解名    

(2) 注解配置参数名为注解类的方法名,且:       

a) 所有方法没有方法体,方法名即为属性名,没有参数没有修饰符,实际只允许 public & abstract 修饰符,默认为 public ,不允许抛异常       

b) 方法返回值只能是基本类型,String, Class, annotation, enumeration 或者是他们的一维数组,返回类型即为属性类型

c) 若只有一个默认属性,可直接用 value() 函数。一个属性都没有表示该 Annotation 为 Mark Annotation      

d) 可以加 default 表示默认值,null不能作为成员默认值

@MethodInfo的调用

public class App {
    @MethodInfo( author =“xiaotian”, date="2014/02/14", version=2)
    public String getAppName() {
        return "trinea";
    }
}

这里是调用自定义Annotation--MethodInfo的示例,MethodInfo Annotation 作用为给方法添加相关信息,包括 author、date、version

再举一个例子

分别定义@name和@sex

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sex {

    public enum GenderType {
        Male("M"),
        Female("F");
        private String genderStr;
        private GenderType(String arg0) {
            this.genderStr = arg0;
        }
        @Override
        public String toString() {
            return genderStr;
        }
    }
    GenderType gender() default GenderType.Male;
}

使用自定义注解的实体类

public class User {

    @Name(value = "wtj")
    public String name;
    public String age;
    @Sex(gender = Sex.GenderType.Male)
    public String sex;

}

测试

public class AnnotionUtils {

    public static String getInfo(Class<?> cs){
        String result = "";
        //通过反射获取所有声明的字段
        Field[] declaredFields = cs.getDeclaredFields();
        //获取所有字段
        for (Field field : declaredFields){
            if(field.isAnnotationPresent(Name.class)){
                //获取程序元素上的注解
                Name annotation = field.getAnnotation(Name.class);
                String value = annotation.value();
                result += (field.getName() + ":" + value + "\n");
            }
            if(field.isAnnotationPresent(Sex.class)){
                Sex annotation = field.getAnnotation(Sex.class);
                String value = annotation.gender().name();
                result += (field.getName() + ":" + value + "\n");
            }
        }
        return result;
    }

    public static void main(String[] args){
        String info = getInfo(User.class);
        System.out.println(info);
    }

}

main方法运行后就可以在控制台中看到使用注解时传入的数据了.
上面就是一个简单的注解使用的demo,当然,在实际工作中使用的会相对复杂,这就需要我们根据业务需求及代码需求进行封装和使用自定义注解了.