参考:https://blog.csdn.net/briblue/article/details/73824058
注解的理解
Java注解,可以简单理解为一个标签,用来标示某个对象。
注解的定义
public @interface TestAnotation
它的声明与接口类似,只是在interface前加上@修饰
注解的属性
id,name,age 只能用java的基本数据类型int,String等
注解的元注解
@Retention
保留期,主要是
RetentionPolicy.RUNTIME 运行中
RetentionPolicy.SOURCE 源代码中
RetentionPolicy.Class 编译期
@Target
指明注解运用的地方
@Documented
关联javadoc
@Repeatable
可重复的
@inherited
继承
注解的应用
注解可以用在类,方法,属性上
@TestAnotation(id = 3, name = "xl")
public class Test {
@Field
private String value;
@Check
public void get(){
}
}
比如一个简单的注解
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Target(value = { ElementType.TYPE })
public @interface TestAnotation {
int id();
String name();
int age() default 18;
}
public static void main(String[] args) {
boolean t = Test.class.isAnnotationPresent(TestAnotation.class);
System.out.println(t);
if(t){
TestAnotation tmp = Test.class.getAnnotation(TestAnotation.class);
System.out.println(tmp.age());
System.out.println(tmp.id());
System.out.println(tmp.name());
Annotation[] a = Test.class.getAnnotations();
for(Annotation annotation : a){
System.out.println("==="+annotation.annotationType().getSimpleName());
}
}
}
Java预置的注解
@Override
@Deprecated
@SuppressWarnings
注解的提取
采用反射提取类,属性,方法值
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
public @interface Fly {
String val() default "f";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
public @interface Check {
String value() default "x";
}
@TestAnotation(id = 3, name = "xl")
public class Test {
@Fly(val="xxx")
public String value;
@Check
public void get(){
}
}
public static void main(String[] args) throws
NoSuchFieldException, SecurityException, NoSuchMethodException {
Field value = Test.class.getDeclaredField("value");
value.setAccessible(true);
Fly c = value.getAnnotation(Fly.class);
if(c != null){
System.out.println(c.val());
}
Method get = Test.class.getDeclaredMethod("get");
if ( get != null ) {
// 获取方法中的注解
Annotation[] ans = get.getAnnotations();
for( int i = 0;i < ans.length;i++) {
System.out.println("method testMethod
annotation:"+ans[i].annotationType().getSimpleName());
}
}
}
运行结果:
xxx
method testMethod annotation:Check
要想获取到运行的结果,注解中的@Retention(RetentionPolicy.RUNTIME)必不可少。