Java 注解全解析
1. 注解的获取与使用
在 Java 中,我们可以使用 getAnnotations()
方法来获取与类或方法相关的所有注解。以下是一个示例代码:
Method m = ob.getClass().getMethod("myMeth");
annos = m.getAnnotations();
System.out.println("All annotations for myMeth:");
for(Annotation a : annos)
System.out.println(a);
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
上述代码通过反射获取 myMeth
方法的所有注解,并将它们打印输出。运行此代码,可能会得到如下输出:
All annotations for Meta2:
@What(description=An annotation test class)
@MyAnno(str=Meta2, val=99)
All annotations for myMeth:
@What(description=An annotation test method)
@MyAnno(str=Testing, val=100)
getAnnotations()
方法返回一个