什么是注解annotation?
在jdk5后出现了注解,注解的出现大大减少了需要注入所写的xml配置。
自定义一个注解
使用关键字@interface声明一个注解
public @interface MyAnnotation
{
String value();
}
annotation的属性
- @Deprecated
标注方法为废弃的方法
@Override
标注方法为重写的方法@SuppressWarnings
@Target
限定注解的使用范围
使用@Target例子
@Target(ElementType.ANNOTATION_TYPE)
public @interface MyTarget
{
String value();
}
范围类型: type,field,method,parameter,constructor,LOCAL_VARIABLE,ANNOTATION_TYPE,PACKAGE
public enum ElementType
{
TYPE, //适用class, interface, enum
FIELD, //适用field
METHOD, //适用method
PARAMETER, //适用method上之parameter
CONSTRUCTOR, //适用构造方法
LOCAL_VARIABLE, //适用局部变量
ANNOTATION_TYPE, //适用annotation型态
PACKAGE //适用package
}
- @Retention
限定注解的使用阶段。
.java源文件==》编译成class==》被虚拟机读取(运行时可读取)
public enum RetentionPolicy
public enum RetentionPolicy
{
SOURCE, //编译程序处理完Annotation信息后就完成任务
CLASS, //编译程序将Annotation储存于class档中,缺省
RUNTIME //编译程序将Annotation储存于class檔中,可由VM读入
}
使用@Retention
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
String hello() default "langsin";
String world();
}
- @Documented
被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化 - @Inherited
标注注解后,如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子 类。简单来说子类继承父类的注解。
声明一个@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface InheritedTest
{
String value();
}
在继承类中体现
@InheritedTest
public class Father{}
public Child extends Father{}
测试在父类和子类中都能获取注解信息
public static void main(String[] args)
{
Class<Parent> c = Parent.class;
if(c.isAnnotationPresent(InheritedTest.class))
{
System.out.println("父类有注解");
}
Class<Child> childClass =Child.class;
if(childClass.isAnnotationPresent(InheritedTest.class))
{
System.out.println("子类有注解");
}
}
通过注释获取信息
获取方法值
MyAnnotation annotation = ShowAnnotation.class.getAnnotation(MyAnnotation.class);
String name = annotation.hello();
使用hibernate注解校验参数
转载https://www.cnblogs.com/mr-yang-localhost/p/7812038.html#_label4
转载https://blog.csdn.net/ruangong1203/article/details/51002360