2012-05-21 58 views
6

如何在注释中设置值?获取注释值?

我有以下注释中定义:

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface JsonElement { 
    int type(); 
} 

这里是使用它在一个POJO类

@JsonElement(type=GETTER_METHOD) 
public String getUsername{ 
........................ 
} 

和使用反射来检查,如果该方法具有UTIL类中的方法出现JSonElement注释并检查类型值是什么。

Method methods[] = classObject.getClass().getDeclaredMethods(); 

     JSONObject jsonObject = new JSONObject(); 
     try { 
      for (int i = 0; i < methods.length; i++) { 
       String key = methods[i].getName(); 
       System.out.println(key); 
       if (methods[i].isAnnotationPresent(JsonElement.class) && key.startsWith(GET_CHAR_SEQUENCE)) { 
        methods[i].getDeclaredAnnotations(); 
        key = key.replaceFirst(GET_CHAR_SEQUENCE, ""); 
        jsonObject.put(key, methods[i].invoke(classObject)); 
       } 

      } 
      return jsonObject; 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } 

我如何知道type()值是什么?我可以找到注释是否存在,但是我找不到找到为type()设置了什么值(如果有)的方法。

回答

16
JsonElement jsonElem = methods[i].getAnnotation(JsonElement.class); 
int itsTypeIs = jsonElem.type(); 

备注你必须通过你的

isAnnotationPresent(JsonElement.class) 

或简单

if (jsonElem != null) { 
} 

检查确保jsonElemnull无论是。


此外,如果你改变了你的注释

public @interface JsonElement { 
    int type() default -1; 
} 

你就不会在你的代码的@JsonElement每一次出现陈述type属性 - 它会默认为-1

你也可以考虑使用它来代替某些整数标志的enum,例如:

public enum JsonType { 
    GETTER, SETTER, OTHER; 
} 

public @interface JsonElement { 
    JsonType type() default JsonType.OTHER; 
} 
+0

是的,我得到它的工作;谢谢。是他们使“type()”成为可选的方法吗?到目前为止,type()必须在JsonElement注释 – jonney

+0

中进行声明,并编辑为答案。 –

3

如果注释属于JSonElement如果是你可以投,并调用你的方法可以检查

如果通过所有的注释循环再

for(Annotation annotation : methods[i].getAnnotations()) { 
    if(annotation instanceOf(JsonElement)){ 
     ((JsonElement)annotation).getType(); 
    } 
} 

JSonElement jSonElement = methods[i].getAnnotations(JSonElement.class); 
jSonElement.getType(); 
2
JsonElement jsonElement = methods[i].getAnnotation(JsonElement.class); 

int type = jsonElement.type(); 
0

解决方案:

Method methods[] = classObject.getClass().getDeclaredMethods(); 

    JSONObject jsonObject = new JSONObject(); 
    try { 
     for (int i = 0; i < methods.length; i++) { 
      String key = methods[i].getName(); 
      System.out.println(key); 
      if (methods[i].isAnnotationPresent(JsonElement.class) 
        && key.startsWith(GET_CHAR_SEQUENCE) 
        && (methods[i].getAnnotation(JsonElement.class).type() == GETTER_METHOD)) { 

       key = key.replaceFirst(GET_CHAR_SEQUENCE, ""); 
       jsonObject.put(key, methods[i].invoke(classObject)); 

      } 

     } 
     return jsonObject; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 
0

从我的理解,你的代码的作用: - 迭代通过声明的方法 - 检查当前方法是否使用JsonElement.class注释,其名称以GET_CHAR_SEQUENCE开头,注释类型的值等于GETTER_METHOD。 - 你根据条件构建你的json

我看不到你正在改变注释本身的类型成员的当前值。看起来像你不需要它了。

但有没有人知道如何得到这个任务整理出来?