java annotation

1 什么是annotationjava

annotation是java编译器支持的一种标记,它能够简化咱们的代码,使得咱们的代码更加方便被理解。网络

2 元annotationspa

用来编写其它注解的注解。code

@Retentionorm

保留期,有三种保留期。继承

RetentionPolicy.SOURCEget

这样的注解只在源码阶段保留,编译器在编译的时候会忽略掉它们。编译器

RetentionPolicy.CLASS源码

编译的时候会用到它们,可是不会加载到虚拟机中。虚拟机

RetentionPolicy.RUNTIME

保留到程序运行的时候,而且加载到虚拟机中,在程序运行的时候能够经过反射获取它们。

@Documented

将注解中的元素加载到javadoc中去。

@Target

指的是注解能够生效的地方,有8种。ElementType.ANNOTATION_TYPE、ElementType.CONSTRUCTOR、ElementType.FIELD、ElementType.LOCAL_VARIABLE、

ElementType.METHOD、ElementType.PACKAGE、ElementType.PARAMETER、ElemenType.TYPE。

@Inherited

指的是子类继承超类的注解。

@Repeatable

能够屡次使用。

3 注解定义的通常形式

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface TestAnnotation {

    int id();

    String msg();

}

4 带成员变量的注解

4.1 定义带成员变量的注解:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface MyTag {

    // 定义两个成员变量,注解的成员变量的定义以方法的形式来定义。

    String name();

    int age default 32;

}

4.2 带成员变量的注解的使用

public class Test {

    @MyTag(name = "Dhello")

    public void info(){}

}

5 注解的提取和使用

5.1 使用的技术

反射。

5.2 判断是否使用了注解

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}

5.3 获取指定的注解

public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}

5.4 获取全部的注解

public Annotation[] getAnnotations() {}

4.5 使用案例

以下例子所示,咱们能够获取类上的注解、方法上的注解以及类的成员变量上的注解(该例子来自于网络)。

@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()); } } 
相关文章
相关标签/搜索