java基础之Annotation

注解的作用
    对元数据提供支持,通过使用注释,程序开发人员可以在不改变原有逻辑的情况下,在源文件
中嵌入一些补充信息
    Class<? extends Annotation> annotationType();
系统内置注解
    @override:覆盖annotation
    @Deprecated:不赞成使用的annotation
@SuppressWarnings:压制安全警告
自定义Annotation
/**
 * 自定义注解
 * @author Administrator
 *@interface 相当于继承annotation
 */
/*public @interface TestAnnotation {
public String value();
}*/
/*public @interface TestAnnotation1{
public String[] value();
}*/
//通过默认值来设置值
/*public @interface TestAnnotation1{
public String value() default "ll";
public String key() default "test";
}*/
//使用枚举类定义注解,来限定值
/*public @interface TestAnnotation1{
public TestAnno value() default TestAnno.LL;
public TestAnno key() default  TestAnno.LL;
}*/
//使用retention 定义注解使用范围
@Documented
@Retention(value=RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestAnnotation1{
public TestAnno value() default TestAnno.LL;
public TestAnno key() default  TestAnno.LL;
}
在annotation中,可以使用Retention定义一个annotation的保存范围
//反射获取所有全部annotation
public class Test1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException {
Class c =Class.forName("com.test.annptation.Stringtest");
Method method = c.getMethod("toString");
Annotation[] annotations = method.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println(annotations[i]);
System.out.println("=============");
}
}
}
public enum TestAnno {
   LL,HELLO;
}
public class Test {
//获取指定annotation指定内容
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException {
Class c =Class.forName("com.test.annptation.Stringtest");
Method method = c.getMethod("toString");
if(method.isAnnotationPresent(TestAnnotation1.class)){
TestAnnotation1 annotation = method.getAnnotation(TestAnnotation1.class);
System.out.println(annotation.key());
System.out.println(annotation.value());
}
}
}
public class Stringtest {
//如果报错,请看对应注解的@target对象是否是否你想要的注解范围
   @TestAnnotation1(key=TestAnno.HELLO,value=TestAnno.LL)
   @Override
    public String toString() {
// TODO Auto-generated method stub
return super.toString();
   }
}
@target 必须指出一个annotation使用位置
@Inherited 用于标注一个父类的注释是否可以被子类所继承。
@Documented
@Inherited
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyInheritedAnnotation {
public String name();
}
@MyInheritedAnnotation(name = "ll")
public class Person {
}
//注释在父类,我们反射子类,如果能够获取注释的内容,那么说明可以注释可以被继承
public static void main(String[] args) throws ClassNotFoundException {
Class<?> c =Class.forName("com.test.annptation.Person");
 
if(c.isAnnotationPresent(MyInheritedAnnotation.class)){
MyInheritedAnnotation annotation = c.getAnnotation(MyInheritedAnnotation.class);
System.out.println(annotation.name()); 
}
}
}

猜你喜欢

转载自blog.csdn.net/yl_hahha/article/details/80204382