java 获取注解_Java的自定义注解及通过反射获取注解

本文详细介绍了Java注解的基本知识,包括元注解@Retention、@Target、@Documented和@Inherited的用法,并展示了如何自定义注解。通过示例展示了如何在类、方法、字段和构造函数上使用注解,并通过反射技术解析和使用这些注解。最后,文章提供了注解的实战应用,包括解析类和方法上的注解信息。
摘要由CSDN通过智能技术生成

一、注解基本知识

1、元注解:@Retention @Target @Document @Inherited

2、Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。

3、参数成员只能用public或默认(default)这两个访问权修饰

4、参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组。

5、要获取类、方法和字段的注解信息,必须通过Java的反射技术来获取 Annotation对象,除此之外没有别的获取注解对象的方法

6、注解也可以没有定义成员, 不过这样注解就没啥用了,只起到标识作用

自定义注解类时, 可以指定目标 (类、方法、字段, 构造函数等) , 注解的生命周期(运行时,class文件或者源码中有效), 是否将注解包含在javadoc中及是否允许子类继承父类中的注解, 具体如下:

1、@Target 表示该注解目标,可能的 ElemenetType 参数包括:

ElemenetType.CONSTRUCTOR 构造器声明

ElemenetType.FIELD 域声明(包括 enum 实例)

ElemenetType.LOCAL_VARIABLE 局部变量声明

ElemenetType.METHOD 方法声明

ElemenetType.PACKAGE 包声明

ElemenetType.PARAMETER 参数声明

ElemenetType.TYPE 类,接口(包括注解类型)或enum声明

2、@Retention 表示该注解的生命周期,可选的 RetentionPolicy 参数包括

RetentionPolicy.SOURCE 注解将被编译器丢弃

RetentionPolicy.CLASS 注解在class文件中可用,但会被JVM丢弃

RetentionPolicy.RUNTIME JVM将在运行期也保留注释,因此可以通过反射机制读取注解的信息

3、@Documented 指示将此注解包含在 javadoc 中

4、@Inherited 指示允许子类继承父类中的注解

二、在java中的使用

2.1、定义注解

packageannotation;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;public classMyAnnotation {/*** 注解类

*

*@authorsuguoliang

**/@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)public @interfaceMyClassAnnotation {

String uri();

String desc();

}/*** 构造方法注解

*

*@authorsuguoliang

**/@Target(ElementType.CONSTRUCTOR)

@Retention(RetentionPolicy.RUNTIME)public @interfaceMyConstructorAnnotation {

String uri();

String desc();

}/*** 方法注解

*

*@authorsuguoliang

**/@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)public @interfaceMyMethodAnnotation {

String uri();

String desc();

}/*** 字段注解

*

*@authorsuguoliang

**/@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)public @interfaceMyFieldAnnotation {

String uri();

String desc();

}/*** 可以同时应用到类和方法上

*

*@author尐蘇

**/@Target({ ElementType.TYPE, ElementType.METHOD })

@Retention(RetentionPolicy.RUNTIME)public @interfaceMyClassAndMethodAnnotation {//定义枚举

public enumEnumType {

util, entity, service, model

}//设置默认值

public EnumType classType() defaultEnumType.util;//数组

int[] arr() default { 3, 7, 5};

String color()default "blue";

}

}

2.2基本测试

packageannotation;importjava.lang.reflect.Constructor;importjava.lang.reflect.Field;importjava.lang.reflect.Method;importannotation.MyAnnotation.MyClassAndMethodAnnotation;importannotation.MyAnnotation.MyClassAndMethodAnnotation.EnumType;importannotation.MyAnnotation.MyClassAnnotation;importannotation.MyAnnotation.MyConstructorAnnotation;importannotation.MyAnnotation.MyFieldAnnotation;importannotation.MyAnnotation.MyMethodAnnotation;

@MyClassAnnotation(desc= "The Class", uri = "com.sgl.annotation")

@MyClassAndMethodAnnotation(classType=EnumType.util)public classTestAnnotation {

@MyFieldAnnotation(desc= "The Class Field", uri = "com.sgl.annotation#id")privateString id;

@MyConstructorAnnotation(desc= "The Class Constructor", uri = "com.sgl.annotation#constructor")publicTestAnnotation() {

}publicString getId() {returnid;

}

@MyMethodAnnotation(desc= "The Class Method", uri = "com.sgl.annotation#setId")public voidsetId(String id) {this.id =id;

}

@MyMethodAnnotation(desc= "The Class Method sayHello", uri = "com.sgl.annotation#sayHello")public voidsayHello(String name) {if (name == null || name.equals("")) {

System.out.println("hello world!");

}else{

System.out.println(name+ "\t:say hello world");

}

}public static void main(String[] args) throwsException {

Class clazz = TestAnnotation.class;//获取类注解

MyClassAnnotation myClassAnnotation = clazz.getAnnotation(MyClassAnnotation.class);

System.out.println(myClassAnnotation.desc()+ "+" +myClassAnnotation.uri());//获得构造方法注解

Constructor constructors = clazz.getConstructor(new Class[] {});//先获得构造方法对象

MyConstructorAnnotation myConstructorAnnotation = constructors.getAnnotation(MyConstructorAnnotation.class);//拿到构造方法上面的注解实例

System.out.println(myConstructorAnnotation.desc() + "+" +myConstructorAnnotation.uri());//获得方法注解

Method method = clazz.getMethod("setId", new Class[] { String.class });//获得方法对象

MyMethodAnnotation myMethodAnnotation = method.getAnnotation(MyMethodAnnotation.class);

System.out.println(myMethodAnnotation.desc()+ "+" +myMethodAnnotation.uri());//获得字段注解

Field field = clazz.getDeclaredField("id");//暴力获取private修饰的成员变量

MyFieldAnnotation myFieldAnnotation = field.getAnnotation(MyFieldAnnotation.class);

System.out.println(myFieldAnnotation.desc()+ "+" +myFieldAnnotation.uri());

}

}

2.3通过反射解析

packageannotation;importjava.lang.reflect.Method;importjava.util.Arrays;importannotation.MyAnnotation.MyClassAndMethodAnnotation;importannotation.MyAnnotation.MyClassAndMethodAnnotation.EnumType;importannotation.MyAnnotation.MyClassAnnotation;importannotation.MyAnnotation.MyMethodAnnotation;public classParseAnnotation {/*** 解析方法注解

*

*@paramclazz*/

public static void parseMethod(Classclazz) {try{

T obj=clazz.newInstance();for(Method method : clazz.getDeclaredMethods()) {

MyMethodAnnotation methodAnnotation= method.getAnnotation(MyMethodAnnotation.class);if (methodAnnotation != null) {//通过反射调用带有此注解的方法

method.invoke(obj, methodAnnotation.uri());

}

MyClassAndMethodAnnotation myClassAndMethodAnnotation=method

.getAnnotation(MyClassAndMethodAnnotation.class);if (myClassAndMethodAnnotation != null) {if(EnumType.util.equals(myClassAndMethodAnnotation.classType())) {

System.out.println("this is a util method");

}else{

System.out.println("this is a other method");

}

System.out.println(Arrays.toString(myClassAndMethodAnnotation.arr()));//打印数组

System.out.println(myClassAndMethodAnnotation.color());//输出颜色

}

System.out.println("\t\t-----------------------");

}

}catch(Exception e) {

e.printStackTrace();

}

}public static void parseType(Classclazz) {try{

MyClassAndMethodAnnotation myClassAndMethodAnnotation=clazz

.getAnnotation(MyClassAndMethodAnnotation.class);if (myClassAndMethodAnnotation != null) {if(EnumType.util.equals(myClassAndMethodAnnotation.classType())) {

System.out.println("this is a util class");

}else{

System.out.println("this is a other class");

}

}

MyClassAnnotation myClassAnnotation= clazz.getAnnotation(MyClassAnnotation.class);if (myClassAnnotation != null) {

System.err.println(" class info: " +myClassAnnotation.uri());

}

}catch(Exception e) {

e.printStackTrace();

}

}public static voidmain(String[] args) {

parseMethod(TestAnnotation.class);

parseType(TestAnnotation.class);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值