public class TestAnnotation { public static void main(String[] args) { A a = new A(); a.method2(); } } class A{ void method1(){} @Deprecated void method2(){} //表示过期的方法,可以用,但是不建议使用 } //在重载方法前面加上override,如果说自己在写重载方法时候不小心把方法名称写错了,比如写成了metode,这时候就会报错 //注意观察重载方法在编译器里前面有一个小三角 class B extends A{ @Override void method1(){} }
比如说我们在定义一个字符串String str = "abc";时,编译器会出现一个警告标志,提醒此变量未被用过,要消除此警告,把鼠标放在左侧边缘的警告处,添加:
public class TestAnnotation { @SuppressWarnings("unused") public static void main(String[] args) { String str = "abc"; } }
首先可以查看一下系统注解的定义
//Override的定义 @Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { } //Target的定义 @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { ElementType[] value(); }
然后我们自定义一个注解:
使用这个注解:
public class TestAnnotation {public static void main(String[] args) { } } //可以用在类,方法.... @HelloAnnotation(name="abc") class A{ @HelloAnnotation() void method1(){} }
import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * 1. 使用 @interface 定义注解 * 2. 使用类似于接口方法声明的方式来定义注解的属性: 其中返回值称为属性的类型, 方法名为属性的名称. * */ @Target(value={ElementType.METHOD, ElementType.TYPE}) public @interface HelloAnnotation { public String name() default "atguigu"; }
提取Annotation 信息(与反射相关)
//只能用来修饰方法和类型(类也是一个类型) @Target(value={ElementType.METHOD, ElementType.TYPE}) public @interface HelloAnnotation { public String name() default "atguigu"; }
?@Documented: 用于指定被该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档.
原文:http://www.cnblogs.com/tech-bird/p/3523290.html