三个常用的注解
@Override
public class OverrideTest { //@Override表示子类要重写基类对应的方法,可以防止出现写错方法名的错误。 @Override public String toString() { return "OverrideTest [toString()=" + super.toString() + "]"; }
public static void main(String[] args) { OverrideTest test = new OverrideTest();
System.out.println(test); } } |
@Deprecated
public class DeprecatedTest { //@Deprecated表示方法是不建议被使用的 @Deprecated public void { System.out.println("do somthing"); }
public static void main(String[] args) { DeprecatedTest test = new test. } }
|
@SuppressWarnings
public class SuppressWarningsTest { //表示抑制警告 @SuppressWarnings({"unchecked","deprecation"}) public static void main(String[] args) { Map map = new HashMap();
map.put("hello",new Date());
System.out.println(map);
Date date = new Date();
System.out.println(date. } } |
自定义注解类型
当我们用@interface关键字去定义一个注解时,该注解隐含地继承了java.lang.annotation.Annotation接口;如果我们定义了一个接口,并且让该接口继承自Annotation,那么我们所定义的依然是接口而不是注解,Annotation本身是接口而不是注解,可以与Enum类比.
public @interface AnnotationTest { String value() default "anllin"; } |
定义注解时,如果属性名为value,则在使用时,可以不用value="class"的形式赋值
可以直接赋值。除value外其他都要用name = value的形式赋值
@AnnotationTest("class") public class AnnotationUsage { @AnnotationTest("method") public static void method() { System.out.println("Hello World"); }
public static void main(String[] args) { method(); } } |
@Retention的使用
@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String hello() default "com.anllin"; String world(); }
|
@MyAnnotation(hello = "shenzhen",world = "futian") public class MyTest { @MyAnnotation(hello = "shanghai" , world = "shangpu") @Deprecated @SuppressWarnings("unchecked") public void { System.out.println("output"); } }
|
java.lang.reflect.AnnotatedElement接口
反射中的Class,Constructor,Field,Mehtod,Package等类别,都实现了AnnotatedElemnet接口。
使用反射获得注解
只有@Retention(RetentionPolicy.RUNTIME)修饰的注解才可以用反射获得,标志发生在运行时。
public class MyReflection { public static void
|