前言
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注解的全部内容啦
原创不易,喜欢请点赞+关注哦
本文介绍了Java注解的基本概念,包括JDK内置注解、自定义注解的创建及使用,以及@Target、@Retention等元注解的作用。通过示例展示了如何使用注解以及如何在代码中获取和处理注解信息。最后,提供了自定义注解@Etoak的实例,并给出了测试代码以演示注解的运行时检查。
6910

被折叠的 条评论
为什么被折叠?



