java注解
注解是一系列元数据,它提供数据用来解释程序代码,但是注解并非是所解释的代码本身的一部分。注解对于代码的运行效果没有直接影响。
注解有许多用处,主要如下:
提供信息给编译器: 编译器可以利用注解来探测错误和警告信息
编译阶段时的处理: 软件工具可以用来利用注解信息来生成代码、Html文档或者做其它相应处理。
运行时的处理: 某些注解可以在程序运行的时候接受代码的提取
值得注意的是,注解不是代码本身的一部分。
像上面这种解释,很正确,但也很晦涩,读一遍却还是很难理解,这里用一种简单的解释方式来解释注解,就是把它认为是 “标签”。
标签应该很好理解,可以有标识的意思,也可以作为分类,有了标签这个概念,理解起来注解就会容易很多了,下面进入正题
定义注解
像下面这样
public @interface TestAnnotation { }
定义注解必须使用@interface,TestAnnotation就是注解的名字,这样一个注解就定义好了,但是要想使用注解,还必须使用元注解
元注解
元注解有 @Retention、@Documented、@Target、@Inherited、@Repeatable 5 种。
元注解的作用就是对自定义的注解进行注解
@Retention
Retention 的英文意为保留期的意思。
当 @Retention 应用到一个注解上的时候,它解释说明了这个注解的的存活时间。
它的取值如下:
- RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。
- RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中。
- RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。
@Retention(RetentionPolicy.RUNTIME) public @interface TestAnnotation { }
@Documented
它的作用是能够将注解中的元素包含到 Javadoc 中去。
@Target
Target 是目标的意思,@Target 指定了注解运用的地方。
你可以这样理解,当一个注解被 @Target 注解时,这个注解就被限定了运用的场景。
类比到标签,原本标签是你想张贴到哪个地方就到哪个地方,但是因为 @Target 的存在,它张贴的地方就非常具体了,比如只能张贴到方法上、类上、方法参数上等等。@Target 有下面的取值
- ElementType.ANNOTATION_TYPE 可以给一个注解进行注解
- ElementType.CONSTRUCTOR 可以给构造方法进行注解
- ElementType.FIELD 可以给属性进行注解
- ElementType.LOCAL_VARIABLE 可以给局部变量进行注解
- ElementType.METHOD 可以给方法进行注解
- ElementType.PACKAGE 可以给一个包进行注解
- ElementType.PARAMETER 可以给一个方法内的参数进行注解
- ElementType.TYPE 可以给一个类型进行注解,比如类、接口、枚举
@Inherited
Inherited 是继承的意思,但是它并不是说注解本身可以继承,而是说如果一个超类被 @Inherited 注解过的注解进行注解的话,那么如果它的子类没有被任何注解应用的话,那么这个子类就继承了超类的注解。
举个例子
@Inherited @Retention(RetentionPolicy.RUNTIME) @interface Test {} @Test public class A {} public class B extends A {}
这样B也拥有Test这个注解
@Repeatable
Repeatable 是可重复的意思。意味着可以多次注解,也就是每次注解取不同的值。
举个例子
@interface Persons { Person[] value(); } @Repeatable(Persons.class) @interface Person{ String role() default ""; } @Person(role="artist") @Person(role="coder") @Person(role="PM") public class SuperMan{ }
Persons是一个注解,是一个容器注解,它的属性中存储Person注解。
@Repeatable后的括号中写的是容器注解这个类,意思是把Repeatable注解了的Person注解放到Persons注解里。
然后在Person注解的属性中可以设置String值,通过person来注解SuperMan
注解的属性
上面已经有使用过注解的属性了。
具体属性的定义就像是方法似的,String role() ;表示属性名为role,类型是String,也可以为其设置默认值,即在后边加default
String role() default "c";
使用注解时就可以在括号中设置属性
@Person(role="artist")
要使用默认值的话就像这样
@Person()
如果注解只有一个属性,那么可以不需要指定属性名了
@Person("artist")
最后如果注解没有任何属性,那么直接像这样
@Person
括号也不需要了
Java 预置的注解
就是现成的注解
@Deprecated
表示标记过时的东西,编译器在编译阶段遇到这个注解时会发出提醒警告,告诉开发者正在调用一个过时的元素比如过时的方法、过时的类、过时的成员变量。
public class Hero { @Deprecated public void say(){ System.out.println("Noting has to say!"); } public void speak(){ System.out.println("I have a dream!"); } }
say就是过时的,speak就不是过时的
显示在idea中就是这样:
@Override
重写
@SuppressWarnings
阻止警告
之前说的使用过时的东西编译器会警告,这时这样使用
@SuppressWarnings("deprecation") public void test1(){ Hero hero = new Hero(); hero.say(); hero.speak(); }
就会组织这个警告
@SafeVarargs
参数安全类型注解。它的目的是提醒开发者不要用参数做一些不安全的操作,它的存在会阻止编译器产生 unchecked 这样的警告
@FunctionalInterface
函数式接口注解,函数式接口 (Functional Interface) 就是一个具有一个方法的普通接口。
@FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
函数式接口可以很容易转换为 Lambda 表达式
提取注解
在把标签贴完之后,就该检查标签了。
检查标签主要通过反射机制来获取。
首先有3个方法
//判断是否应用了某个注解 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {} //获取注解对象 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {} //获取多个注解对象 public Annotation[] getAnnotations() {}
使用举例:
@TestAnnotation() public class Test { public static void main(String[] args) { boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class); if ( hasAnnotation ) { TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class); System.out.println("id:"+testAnnotation.id()); System.out.println("msg:"+testAnnotation.msg()); } } }
当然不只是类的注解,属性,方法同样可以检查,还是要依赖于反射
@TestAnnotation(msg="hello") public class Test { @Check(value="hi") int a; @Perform public void testMethod(){} @SuppressWarnings("deprecation") public void test1(){ Hero hero = new Hero(); hero.say(); hero.speak(); } public static void main(String[] args) { boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class); if ( hasAnnotation ) { TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class); //获取类的注解 System.out.println("id:"+testAnnotation.id()); System.out.println("msg:"+testAnnotation.msg()); } try { Field a = Test.class.getDeclaredField("a"); a.setAccessible(true); //获取一个成员变量上的注解 Check check = a.getAnnotation(Check.class); if ( check != null ) { System.out.println("check value:"+check.value()); } Method testMethod = Test.class.getDeclaredMethod("testMethod"); if ( testMethod != null ) { // 获取方法中的注解 Annotation[] ans = testMethod.getAnnotations(); for( int i = 0;i < ans.length;i++) { System.out.println("method testMethod annotation:"+ans[i].annotationType().getSimpleName()); } } } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } } }
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h57025.shtml