Java 注解(Annotation)(二)

自定义注解

关键字 @interface
public @interface Test {}

// Annotation 中的成员变量以方法的形式来定义
public @interface MyAnnotation {
	String name();
	int age() default 18; // 使用default 定义初始值
}
提取Annotation信息

使用Annotation注解后,注解不会自己沈潇潇,需要使用工具来提取注解信息,例如反射。

java.lang.reflect 包下的 AnnotationElement 接口

实现类:

public interface AnnotatedElement {
...
}
  • AccessibleObject(可访问对象,如:方法、构造器、属性等)
  • Class(类,就是你用Java语言编程时每天都要写的那个东西)
  • Constructor(构造器,类的构造方法的类型)
  • Executable(可执行的,如构造器和方法)
  • Field(属性,类中属性的类型)
  • Method(方法,类中方法的类型)
  • Package(包,你每天都在声明的包的类型)
  • Parameter(参数,主要指方法或函数的参数,其实是这些参数的类型)

这里推荐一个Reflections工具包,反射用。

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.11</version>
</dependency>

代码

Reflections reflections = new Reflections("java.lang.reflect.*");
Set<Class<? extends AnnotatedElement>> subTypes = reflections.getSubTypesOf(AnnotatedElement.class);
subTypes.forEach(x -> System.out.println(x.getName()));
// 打印结果
====================================================
java.lang.reflect.Method
java.lang.reflect.Executable
java.lang.reflect.AnnotatedParameterizedType
java.lang.reflect.TypeVariable
java.lang.reflect.Parameter
java.lang.reflect.Constructor
java.lang.reflect.AccessibleObject
java.lang.reflect.Field
java.lang.reflect.AnnotatedTypeVariable
java.lang.reflect.AnnotatedType
java.lang.reflect.AnnotatedWildcardType
java.lang.reflect.GenericDeclaration
java.lang.reflect.AnnotatedArrayType

只有在Annotation定义为运行时,Annotation才会在运行时可见,JVM才会在加载 *.class 文件时读取保存在 class 文件中的 Annotation。

AnnotatedElement 定义的三个方法:

default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
    return getAnnotation(annotationClass) != null;
}

<T extends Annotation> T getAnnotation(Class<T> annotationClass);

Annotation[] getAnnotations();

Example:

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

public class A implements AA {
    @Override
    @MyAnnotationMethod
    public void say() {
        System.out.println("A");
    }

}

Annotation[] array = Class.forName("com.beng.annotation.A").getMethod("say").getAnnotations();
Arrays.asList(array).forEach(x -> System.out.println("A :" + x.annotationType()));
for (Annotation a : array) {
    if (a instanceof MyAnnotationMethod) {
        System.out.println("A MyAnnotationMethod name:" + ((MyAnnotationMethod) a).name());
    }
}

==============================
A :interface com.beng.annotation.MyAnnotationMethod
A MyAnnotationMethod name:test
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值