正文
getAnnotation(class): 按照传入的参数获取指定类型的注解。返回null说明当前元素不带有此注解。
class 通过java.lang.Class被实现,java.lang.reflect.Method 和 java.lang.reflect.Field,所以可以基本上被和任何Java元素使用。
现在,我们将看一个怎么读取注解的例子:
我们写一个程序,从一个类和它的方法中读取所有的存在的注解:
public static void main( String[] args ) throws Exception
{
Class
object = AnnotatedClass.class;
// Retrieve all annotations from the class
Annotation[] annotations = object.getAnnotations();
for( Annotation annotation : annotations )
{
System.out.println( annotation );
}
// Checks if an annotation is present
if( object.isAnnotationPresent( CustomAnnotationClass.class ) )
{
// Gets the desired annotation
Annotation annotation = object.getAnnotation( CustomAnnotationClass.class );
System.out.println( annotation );
}
// the same for all methods of the class
for( Method method : object.getDeclaredMethods() )
{
if( method.isAnnotationPresent( CustomAnnotationMethod.class ) )
{
Annotation annotation = method.getAnnotation( CustomAnnotationMethod.class );
System.out.println( annotation );
}
}
}
输出如下:
@com.danibuiza.javacodegeeks.customannotations.CustomAnnotationClass(getInfo=Info, author=danibuiza, date=2014-05-05)
@com.danibuiza.javacodegeeks.customannotations.CustomAnnotationClass(getInfo=Info, author=danibuiza, date=2014-05-05)
@com.danibuiza.javacodegeeks.customannotations.CustomAnnotationMethod(author=friend of mine, date=2014-06-05, description=annotated method)
@com.danibuiza.javacodegeeks.customannotations.CustomAnnotationMethod(author=danibuiza, date=2014-06-05, description=annotated method)
在这个程序中,我们可以看到 getAnnotations()方法来获取所有某个对象(方法,类)上的所有注解的用法。展示了怎样使用isAnnotationPresent()方法和getAnnotation()方法检查是否存在特定的注解,和如何获取它。
11. 注解中的继承
注解在Java中可以使用继承。这种继承和普通的面向对象继承几乎没有共同点。
如果一个注解在Java中被标识成继承,使用了保留注解@Inherited,说明它注解的这个类将自动地把这个注解传递到所有子类中而不用在子类中声明。通常,一个类继承了父类,并不继承父类的注解。这完全和使用注解的目的一致的:提供关于被注解的代码的信息而不修改它们的行为。
我们通过一个例子更清楚地说明。首先,我们定义一个自动继承的自定义注解。
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InheritedAnnotation
{
}
有一个父类名为:AnnotatedSuperClass,已经被自定义的注解给注解上了:
@InheritedAnnotation
public class AnnotatedSuperClass
{
public void oneMethod()
{
}
}
一个子类继承父类:
@InheritedAnnotation
public class AnnotatedSuperClass
{
public void oneMethod()
{
}
}
子类 AnnotatedSubClass 展示了自动继承的注解 @InheritedAnnotation。我们看到下面的代码通过 isAnnotationPresent() 方法测试出了当前注解。
System.out.println( "is true: " + AnnotatedSuperClass.class.isAnnotationPresent( InheritedAnnotation.class ) );
System.out.println( "is true: " + AnnotatedSubClass.class.isAnnotationPresent( InheritedAnnotation.class ) );
输出如下:
is true: true
is true: true