java用 @interface Annotation{ } 定义一个注解 @Annotation,一个注解是一个类。注解相当于一种标记,在程序中加上了注解就等于为程序加上了某种标记,以后,JAVAC编译器,开发工具和其他程序可以用反射来了解你的类以及各种元素上有无任何标记,看你有什么标记,就去干相应的事
下面我用代码理清使用步骤:
第一步:(创建@interface注解类)
在进行创建注解类之前,需要在注解类的上方进行元注解(注解的注解)
Documented与Inherited是典型的标识性注解,也就是说在注解内部并没有成员变量,没有成员变量的注解称为标识注解
Documented
指明拥有这个注解的元素可以被javadoc此类的工具文档化。这种类型应该用于注解那些影响客户使用带注释的元素声明的类型。如果一种声明使用Documented进行注解,这种类型的注解被作为被标注的程序成员的公共API 。
Inherited
指明该注解类型被自动继承。如果用户在当前类中查询这个元注解类型并且当前类的声明中不包含这个元注解类型,那么也将自动查询当前类的父类是否存在Inherited元注解,这个动作将被重复执行知道这个标注类型被找到,或者是查询到顶层的父类。
Retention
指明在什么级别显示此注解
Retention主要的参数类型包括以下几种:
RetentionPolicy.SOURCE 注解存在于源代码中,编译时会被抛弃
RetentionPolicy.CLASS 注解会被编译到class文件中,但是JVM会忽略
RetentionPolicy.RUNTIME JVM会读取注解,同时会保存到class文件中
Target
指明该类型的注解可以注解的程序元素的范围
Target主要的参数类型包括以下几种:
ElementType.TYPE 用于类,接口,枚举但不能是注解
ElementType.FIELD 作用于字段,包含枚举值
ElementType.METHOD 作用于方法,不包含构造方法
ElementType.PARAMETER 作用于方法的参数
ElementType.CONSTRUCTOR 作用于构造方法
ElementType.LOCAL_VERIABLE 作用于本地变量或者catch语句
ElementType.ANNOTATION_TYPE 作用于注解
ElementType.PACKAGE 作用于包
如我创建的一个注解类:
@Documented //标识注解。表示没有成员变量
@Target({ElementType.METHOD}) //作用范围。这里作用于方法上
@Retention(RetentionPolicy.RUNTIME) //JVM会读取注解,同时会保存到class文件中
public @interface MethodAnnotation {
String value() default "This is a MethodAnnotation";
String url() default "www.baidu.com";
}
第二步:创建实体类
@TypeAnnotation(value = "do worker") //使用TypeAnnotation注解表示。这里的TypeAnnotation也是一个注解类
public class Worker {
@FiledAnnotation(value = "kaiX")//如果里面没有填写value值
// 如:@FiledAnnotation()它会默认值为@FiledAnnotationl里面的default值
private String myName="";
@MethodAnnotation()
private String getDefaultMethod(){
return "This is a no have cs method";
}
@MethodAnnotation(value = "Method",url = "www.csdn.com")
private String getDefinedMethod(){
return "This is a have cs method";
}
}
第三步:进行测试获取数据
public class TestAnnotation {
public static void main(String[] args) throws ClassNotFoundException {
//通过反射得到Worker类。
Class<?> aClass = Class.forName("com.test.dto.Worker");
//得到Worker类中的所有方法。
Method[] method = aClass.getMethods();
//判断Worker类中是否有TypeAnnotation注解类
boolean flag=aClass.isAnnotationPresent(TypeAnnotation.class);
if(flag){
TypeAnnotation typeAnnotation = aClass.getAnnotation(TypeAnnotation.class);
System.out.println("@TypeAnnotation的值"+typeAnnotation.value());
}
//同理
List<Method> methodList=new ArrayList<>();
for (int i = 0; i <method.length ; i++) {
methodList.add(method[i]);
}
for (Method m:methodList){
MethodAnnotation methodAnnotation = m.getAnnotation(MethodAnnotation.class);
if(methodAnnotation==null){
continue;
}
System.out.println("方法名称"+m.getName());
System.out.println("方法上注解值"+methodAnnotation.value());
System.out.println("方法上地址值"+methodAnnotation.url());
}
for (Field f:aClass.getDeclaredFields()){
FiledAnnotation filedAnnotation = f.getAnnotation(FiledAnnotation.class);
System.out.println("属性名称"+f.getName());
System.out.println("属性上注解值"+filedAnnotation.value());
}
}
}