写注解

Java 四个元注解

@Target 说明要注解的对象 ElementType.CONSTRUCTOR(构造器) , ElementType.FIELD(作用域) , ElementType.LOCALVARIBLE(局部变量) , ElementType.METHOD(方法) , ElementType.PACKAGE(包) , ElementType.PARAMETER(参数) , ElementType.TYPE(类,接口,枚举)

@Retention 说明保留时间 @Retention(RetentionPolicy.RUNTIME) 运行时有效 @Retention(RetentionPolicy.SOURCE)源文件中有效 @Retention(RetentionPolicy.CLASS)类中有效 

@Documented 表示可被工具文档化

@Inherited 表示他的子类也会被注解

写两个注解

package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationClass {
    public String abc() default "";
}
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
package annotation;

@AnnotationClass(abc="Example")
public class Example {
	@AnnotationMethod(abd="abd")
	public void abd(){
		
	}
}

 

public @interface AnnotationMethod { public String abd() default ""; }
//测试得到
public class Test {
    public static void main(String[] args) {
        //AnnotationClass annotations=Example.class.getAnnotation(AnnotationClass.class);
        //System.out.println(annotations.abc());
        /*try {
            Method method=Example.class.getMethod("abd");
            AnnotationMethod annotations=method.getAnnotation(AnnotationMethod.class);
            System.out.println(annotations.abd());
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        
    }
}

posted on 2016-11-24 16:17  flovato  阅读(98)  评论(0编辑  收藏  举报

导航