自定义注解要从注解来说
注解我理解分为
1:jdk定义的注解
2:自定义注解(也就是我们的定义的注解)
注意:jdk定义的注解不用说jdk能识别那我们定义的注解
那我们自定定义注解java怎么识别呢这个就需要依赖元注解来注解我们自定义的注解了才能被jdk识别
注解目录结构为
Annotation(注解)
@Target
@Retention
@Document
@INherited
从JDK 1.5开始, Java增加了对元数据(MetaData)的支持,也就是 Annotation(注解)。
注解其实就是代码里的特殊标记,它用于替代配置文件:传统方式通过配置文件告诉类如何运行,有了注解技术后,开发人员 可以通过注解告诉类如何运行。在Java技术里注解的典型应用是:可以通过反射技术去得到类里面的注解,以决定怎么去运行类。
注解可以标记在包、类、属性、方法,方法参数以及局部变量上,且同一个地方可以同时标记多个注解。
java提供的注解有时候可能不够灵活所以我们可以自定义注解
常用的几个@Target 描述注解的使用范围(即:被修饰的注解可以用在什么地方该范围可以指定多个)
public enum ElementType { TYPE, // 类、接口、枚举类 FIELD, // 成员变量(包括:枚举常量) METHOD, // 成员方法 PARAMETER, // 方法参数 CONSTRUCTOR, // 构造方法 LOCAL_VARIABLE, // 局部变量 ANNOTATION_TYPE, // 注解类 PACKAGE, // 可用于修饰:包 TYPE_PARAMETER, // 类型参数,JDK 1.8 新增 TYPE_USE // 使用类型的任何地方,JDK 1.8 新增 }
@Rentention 描述注解保留的时间范围(即:被描述的注解在它所修饰的类中可以被保留到何时)
public enum RetentionPolicy { SOURCE, // 源文件保留 CLASS, // 编译期保留,默认值 RUNTIME // 运行期保留 }
@Document 描述在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息。(这个小弟占时没有实测过有兴趣的童鞋可以去试试)
@INherited 表示他修饰的类具有继承性,(即某个类使用了被这注解修饰的注解,那么其子类都继承了这个注解)
说这么多上代码测试下
package com.lhz;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
public String name() default "java最牛皮";
}
package com.lhz;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@MyAnnotation(name="类")
public class Demo{
@MyAnnotation(name="方法")
public String say() {
return "看这篇博客的都很帅";
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
Class<Demo> demo= Demo.class;
// 获取类上的所有注解
Annotation[] annotations = demo.getAnnotations();
for (Annotation annotation : annotations) {
// 获取注解的全类名
System.out.println(annotation.annotationType().getName());
}
// 获取 say() 方法
Method method = annotationTest.getMethod("say", new Class[] {});
// say() 方法上是否有 MyAnnotation 注解
if (method.isAnnotationPresent(MyAnnotation.class)) {
// 获得注解
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
// 获取注解的内容
System.out.println(annotation.name());
}
}
}
运行结果
-
package com.lhz;
-
方法