常见注解分类
- Java自带的标准注解
- @Override:重写
- @Deprecated:过时
- @SuppressWarrnings:忽略警告
- 元注解
- @Retention:用于标明注解被保留的阶段
- SOURCE:源文件保留
- CLASS:编译器保留,默认值
- RUNTIME:运行期间保留,可通过反射去获取注解信息
- @Target:用于标明注解使用的范围
- TYPE:类,接口,枚举类
- FIELD:成员变量
- METHOD:成员方法
- PARAMTER:方法参数
- CONSTRUCTOR:构造方法
- LOCAL_VARIABLE:局部变量
- ANNOTATION_TYPE:注解类
- PACKAGE:包
- TYPE_PARAMETER
- TYPE_USE:任何地方
- @Inherited:用于标明注解可继承
- @Documented:用于标明是否生成javadoc文档
- @Retention
- @Retention:用于标明注解被保留的阶段
- 自定义注解
注意:注解不支持继承
例子
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyMethodAnnotation {
String title() default "";
String description() default "";
}
class TestAnnotation {
@Override
@MyMethodAnnotation(title = "toString method", description = "override toString method")
public String toString() {
return "Override toString method";
}
@Deprecated
@MyMethodAnnotation(title = "old static method", description = "deprecated old static method")
public static void oldMethod() {
System.out.println("old method, don't use it.");
}
@SuppressWarnings({"unchecked", "deprecation"})
@MyMethodAnnotation(title = "test method", description = "suppress warning method")
public static void genericsTest() {
List l = new ArrayList();
l.add("abc");
oldMethod();
}
}
@Test
public void testAnnotation() {
try {
Method[] methods = TestAnnotation.class.getClassLoader()
.loadClass("com.afabao.learn.sys.TestAnnotation")
.getMethods();
for (Method method : methods) {
// 方法上是否有MyMethodAnnotation注解
if(method.isAnnotationPresent(MyMethodAnnotation.class)) {
for (Annotation declaredAnnotation : method.getDeclaredAnnotations()) {
System.out.println(method + ":" + declaredAnnotation);
}
}
MyMethodAnnotation annotation = method.getAnnotation(MyMethodAnnotation.class);
System.out.println(annotation.title() + ":" + annotation.description());
}
} catch (Exception e) {
}
}
// 输出:
// public static void com.afabao.learn.sys.TestAnnotation.oldMethod():@java.lang.Deprecated()
// public static void com.afabao.learn.sys.TestAnnotation.oldMethod():@com.afabao.learn.sys.MyMethodAnnotation(title=old static method, description=deprecated old static method)
// old static method:deprecated old static method
// public static void com.afabao.learn.sys.TestAnnotation.genericsTest():@com.afabao.learn.sys.MyMethodAnnotation(title=test method, description=suppress warning method)
// test method:suppress warning method
// public java.lang.String com.afabao.learn.sys.TestAnnotation.toString():@com.afabao.learn.sys.MyMethodAnnotation(title=toString method, description=override toString method)
// toString method:override toString method
标签:toString,Java,MyMethodAnnotation,基础,public,static,注解,method
From: https://www.cnblogs.com/afabao/p/17096839.html