如何在对象java中获取注释

时间:2015-02-17 13:08:20

标签: java annotations

我正在使用一个逻辑,但我不知道是否可以这样做,我想为此使用注释,所以这是我的代码

public class Hola {
    public JSONConverter() {
        String message=  getClass().getAnnotation(HolaAn.class).getMessage();

    }
}


@Target({ElementType.FIELD})
public @interface HolaAn{

    String getMessage();
}




public class MessageTest{

@HolaAn(getMessage= "MUNDO")
private Hola hola;

    @Test
    public void testMessage(){
        hola= new Hola();

    }


}

但是我有nullPointerException,我不知道如何使用我自己的注释,任何人都可以说我是否有可能以及如何做到这一点?

2 个答案:

答案 0 :(得分:2)

您应该将注释更改为

@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface HolaAn {
    String getMessage();
}

这是将注释编译到类文件所必需的。

现在您可以通过以下方式访问您的消息:

Field declaredField = new MessageTest().getClass().getDeclaredField(
        "hola");
System.out.println((declaredField.getDeclaredAnnotation(HolaAn.class)
        .getMessage()));

答案 1 :(得分:2)

首先,您需要将注释保留更改为RUNTIME(默认为CLASS),so they may be read reflectively。改为这样:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface HolaAn {

    String message();

}

您正在尝试从类中获取注释,但您的注释位于字段上,是唯一的元素目标。在此示例中,您可以通过以下方式获取注释:

@HolaAn(message = "MUNDO")
private Hola hola;

@Test
public void testMessageOnField() {
    final Field[] fields = HolaTest.class.getDeclaredFields();
    for (final Field field : fields) {
        if (field.isAnnotationPresent(HolaAn.class)) {
            final HolaAn annotation = field.getAnnotation(HolaAn.class);
            Assert.assertTrue(annotation.message().equals("MUNDO"));
        }
    }
}

如果您需要从类中获取注释,请将其更改为以下内容:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface HolaAn {

    String message();

}

然后,您可以获得这样的注释消息:

@HolaAn(message = "CLASS")
public class Hola {

    public Hola() {
        final String message = this.getClass().getAnnotation(HolaAn.class).message();
        System.out.println(message);
    }

}

@Test
public void testMessage() {
    hola = new Hola();
}

或者:

@Test
public void testMessageSecondWay() {
    hola = new Hola();
    final Class<?> theClass = hola.getClass();
    if (theClass.isAnnotationPresent(HolaAn.class)) {
        final HolaAn annotation = theClass.getAnnotation(HolaAn.class);
        Assert.assertTrue(annotation.message().equals("CLASS"));
    }
}
相关问题