Created
March 24, 2018 08:04
-
-
Save AhianZhang/e4ddf34b369917d20a6919bc8ca5692e to your computer and use it in GitHub Desktop.
Java自定义注解
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test; | |
import java.lang.annotation.*; | |
/** | |
* 自定义注解 | |
* Created by AhianZhang on 2018/3/24. | |
*/ | |
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})//限定注解的使用范围,详见 ElementType | |
@Retention(RetentionPolicy.RUNTIME)//三种 Source:只在源码显示,编译时会丢弃; | |
// Class 编译时会记录到 class 中,运行时会忽略;Runtime:运行时存在,可以读取反射。 | |
@Inherited //允许子类继承,继承时只会继承类上的注解,而不会继承方法上的注解,在接口上的注解无效 | |
@Documented //生成文档用,包含注解 | |
public @interface AnnoDemo | |
{ | |
String value() default "Ahian"; | |
} |
Author
AhianZhang
commented
Mar 24, 2018
•
package com.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 通过反射获取注解
* Created by AhianZhang on 2018/3/24.
*/
public class GetAnno
{
public static void main(String[] args) throws Exception
{
//反射获取到使用的注解类
Class cls = Class.forName("com.test.AnnoTest");
//判断此类上是否存在自定义注解
boolean isExist = cls.isAnnotationPresent(AnnoDemo.class);
if (isExist)
{
//获取类上注解的内容
AnnoDemo ad = (AnnoDemo) cls.getAnnotation(AnnoDemo.class);
System.out.println(ad.value());
}
//获取成员上的注解
Field[] fields = cls.getFields();
//方法一
for (Field field : fields)
{
boolean isFieldExist = field.isAnnotationPresent(AnnoDemo.class);
if (isFieldExist)
{
AnnoDemo annoDemo = field.getAnnotation(AnnoDemo.class);
System.out.println(annoDemo.value());
}
}
//方法二
/* for (Field f:fields){
Annotation[] at = f.getAnnotations();
for (Annotation annotation:at){
if (annotation instanceof AnnoDemo){
AnnoDemo annoDemo = (AnnoDemo) annotation;
System.out.println(annoDemo.value());
}
}
}*/
//获取方法上的注解
Method[] methods = cls.getMethods();
for (Method method : methods)
{
boolean isMethodExist = method.isAnnotationPresent(AnnoDemo.class);
if (isMethodExist)
{
AnnoDemo annoDemo = method.getAnnotation(AnnoDemo.class);
System.out.println(annoDemo.value());
}
}
}
}
这是类上的注解
Ahian
这是在成员上的注解
Ahian
这是在成员上的注解
这是方法上的注解
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment