前言
Q:什么是注解?
A:@interface 是四大类之一,关键字:Annotation,它是写在类中的注解,它是给类看的而不是给人看的注释
1.JDK中提供了一些注解,比如@Override @Deprecated...
2.自定义注解 关键字@interface
Marker annotation
String value() default "" @xx("value属性可以不写")
3.java.lang.annotation子包中的注解
@Target:表示注解适用的程序元素,有一个value属性,ElementType属性是个枚举
@Retention:表示注解保留策略 value属性 SOURCE/CLASS/RUNTIME
@Documented:注解信息允许生成文档
关键字:getAnnotations()----Annotation[]
可以Method或者Class可以直接调用获取自己头顶上的注解;
例子:写一个@Etoak注解
@Target(ElementType.Method)
@Retention(RetentionPolicy.Runtime)
public @interface Etoak{
String value();
}
测试类
public class test{
@Etoak("张三")
public show(){
System.out.println("show...")
}
}
测试代码
Class cls =test.class;
Method[] ms = cls.getDeclaredMethods();
for(Method m :ms){
Annotation[] ans =m.getDeclaredAnnotations();
for(Annotation an:ans){
if(an.annotationType==Etoak.class){
m.invoke(new test);//打印show...
}
}
}
总结
这就是关于java注解的全部内容啦
原创不易,喜欢请点赞+关注哦