我正在尝试在java中使用自定义注释。但是无法获得注释

时间:2016-07-29 09:04:55

标签: java annotations

贝娄是我的自定义注释: -

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

    int width() default 20;
    int length() default 20;
    String placeholder();
    String title();
    String friendlyName();
    String name();

}

我在这里使用注释: -

public class Table {

    private long id;

    @InputBox(width = 25 ,length = 25, placeholder = "" , title = "" , friendlyName = "" , name = "")
    public String name;

    @InputBox(length = 10,placeholder = "",title = ""  , friendlyName = "" , name = "")
    private int age;}}

Parser: - 这里我传递className来获取注释细节但不能获得注释和isAnnotationPresent方法给出空指针异常 -

public JSONArray getFormMetaData(String className) throws InvocationTargetException, IllegalAccessException {
        Class cl = null;
        try{
            cl = Class.forName(className);
        } catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        JSONArray jsonArray = new JSONArray();

        for(Field f: cl.getDeclaredFields())
        {
            if( f.getDeclaredAnnotations().length >0 ){
                if(f.isAnnotationPresent(InputBox.class)){
                    JSONObject obj = AnnotationProcessor.processInputBoxAnnotation(f);
                    obj.put("type","text");
                    jsonArray.add(obj);
                }}}

当我在静态主方法中访问相同的注释时,我得到了正确的结果。例如: -

public class Main {

public static void main(String[] args) {


    Table.class.getDeclaredFields()[1].getDeclaredAnnotations();

}

}

但是当我试图通过api调用结果时,我没有得到任何注释。

1 个答案:

答案 0 :(得分:0)

我只是在你的Table Class中进行main方法测试,其工作正常,请参考下面的代码。

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Table {

    private long id;

    @InputBox(width = 25, length = 25, placeholder = "", title = "", friendlyName = "", name = "")
    public String name;

    @InputBox(length = 10, placeholder = "", title = "", friendlyName = "", name = "")
    private int age;

    public void testAnnotation(String className) throws InvocationTargetException, IllegalAccessException {
        Class cl = null;
        try {
            cl = Class.forName(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        for (Field f : cl.getDeclaredFields()) {
            if (f.getDeclaredAnnotations().length > 0) {
                if (f.isAnnotationPresent(InputBox.class)) {
                    System.out.println("annotationPresent");
                }
            }
        }



    }
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

        new Table().testAnnotation(Table.class.getName());
    }
}