`
liulanghan110
  • 浏览: 1063953 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

注解annotation

    博客分类:
  • JAVA
 
阅读更多

ava注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。

1、元注解

元注解是指注解的注解。包括  @Retention @Target @Document @Inherited四种。


1.1、@Retention: 定义注解的保留策略

@Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
1.2、@Target:定义注解的作用目标

@Target(ElementType.TYPE)   //接口、类、枚举、注解

@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR)  //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///   
 由以上的源码可以知道,他的elementType 可以有多个,一个注解可以为类的,方法的,字段的等等
1.3、@Document:说明该注解将被包含在javadoc中
 
1.4、@Inherited:说明子类可以继承父类中的该注解
 

自定义annotation使用三步曲

1.define annotation interface 

2.define parser annotation class 

3.use annotation and it's parser

 

例子如下:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface HelloWorld {
	public String name()default "";
}

 

public class ParseAnnotation {
	 
    public void parseMethod(Class clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException{
 Object obj = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
   for(Method method : clazz.getDeclaredMethods()){
       HelloWorld say = method.getAnnotation(HelloWorld.class);
       String name = "";
       if(say != null){
          name = say.name();
          method.invoke(obj, name);
       }
     }
   }
}

 

public class SayHello {
	
    @HelloWorld(name = " 小明 ")
    public void sayHello(String name){
        if(name == null || name.equals("")){
            System.out.println("hello world!");
        }else{
            System.out.println(name + "say hello world!");
        }
    }
	
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException {
        ParseAnnotation parse = new ParseAnnotation();
        parse.parseMethod(SayHello.class);
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics