2014-10-29 87 views
0

我想使用的方法的execute()以下类:获取属性标注值

public class Parser { 
    @Header("header1") 
    private String attribute1; 

    @Header("header2") 
    private String attribute2; 

    @Header("header3") 
    private String attribute3; 

    @Header("header4") 
    private String attribute4; 

    public String execute(String headerValue) { 
     //Execute 
    } 
} 

我想这是什么方法来实现在列表中的一个匹配headerValue参数@Header注解,并返回相应属性的值。例如,如果我叫执行(“header3”),它应该返回的attribute3

值我怎样才能做到这一点?或者是更好的方式来编码这个要求?

+0

我期待着用这个来清洁一些东西。显然情况并非如此。你愿意详细说明吗? – 2014-10-29 16:04:15

回答

0

为什么你不使用地图呢?为了存储注释参数值到字段的映射,反正你需要一个,但如果你可以不经过反射就可以做到这一点,它应该更容易编码和维护。

我的意思是:

Map<String, String> attributes; //initialized 

attributes.put("header1", value1); 
... 

在​​你然后就进入地图。

你可以使用枚举来改进它,以限制可能值的数量。

事情是这样的:

enum HeaderType { 
    HEADER1, 
    HEADER2, 
    ... 
} 

private Map<HeaderType, String> headerAttribs = ...; 

void setAttrib(HeaderType type, String value) { 
    headerAttribs.put(type, value); 
} 

String getAttrib(HeaderType type) { 
    return headerAttribs.get(type); 
} 

public String execute(HeaderType type) { 
    //Execute 
} 

如果你需要使用一个字符串,你可以考虑使用一个额外的地图与字符串>头型先查找正确类型的头型。

或者,您可以使用switch语句,因为Java 7应该也可以使用字符串。

0

试试这个:

public String execute(String headerValue) throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException { 
    for(Field field:this.getClass().getFields()) { 
    if (field.isAnnotationPresent(Header.class)) { 
      Header annotation = field.getAnnotation(Header.class); 

      String name = annotation.value(); 
      if(name.equals(headerValue)) { 
      Object val = this.getClass().getField(name).get(this); 
      return (String) val; 
      } 
      } 
    }  
    return null; 
} 

有几个例外的行处理。

对象VAL = this.getClass()getfield命令(名)获得(本);

如果您不想从此方法中抛出该异常,则可以返回null。

0
This may help you 


    Field f[]= Parser.class.getDeclaredFields(); 
    for (int i = 0; i < f.length; i++) { 

    Annotation annotation[]= f[i].getAnnotations(); 
    for (int j=0;j<annotation.length;j++){ 

    Class<Annotation> type = (Class<Annotation>) annotation[j].annotationType();    

     for (Method method : type.getDeclaredMethods()) { 

      if(method.getName() .equals(headerValue)) 
      { 
      String name=f[i].getName(); 
      return name; 
      } 
     } 

    } 
    } 

Parser.class.getDeclaredFields()也会包含专用字段。