2015-04-23 44 views
3

我有一些Java中方法的類如下:如何在java中獲得特殊的類方法?

public class Class1 
{ 
    private String a; 
    private String b; 


    public setA(String a_){ 
     this.a = a_; 
    } 

    public setb(String b_){ 
     this.b = b_; 
    } 

    public String getA(){ 
     return a; 
    } 

    @JsonIgnore 
    public String getb(){ 
     return b; 
    } 
} 

我想在Class1,它使用的是不與@JsonIgnore註解來聲明字符串get開始的所有方法。

我該怎麼做?

+0

你會從中得到一些想法:http://stackoverflow.com/questions/6593597/java-seek-a-method-with-specific-annotation-and-its-annotation-element – RahulArackal

+0

我m猜你正在嘗試將java類轉換爲json。試試這個庫http://flexjson.sourceforge.net/。它處理多個級別,自定義轉換和包含/排除路徑。 – Goose

回答

4

您可以使用Java反射來遍歷所有的公共和私有方法:

Class1 obj = new Class1(); 

Class c = obj.getClass(); 
for (Method method : c.getDeclaredMethods()) { 
    if (method.getAnnotation(JsonIgnore.class) == null && 
     method.getName().substring(0,3).equals("get")) { 
     System.out.println(method.getName()); 
    } 
} 
2

您可以使用java反射。例如,

import static org.reflections.ReflectionUtils.*; 

    Set<Method> getters = getAllMethods(someClass, 
      withModifier(Modifier.PUBLIC), withPrefix("get"), withParametersCount(0)); 

    //or 
    Set<Method> listMethods = getAllMethods(List.class, 
      withParametersAssignableTo(Collection.class), withReturnType(boolean.class)); 

    Set<Fields> fields = getAllFields(SomeClass.class, withAnnotation(annotation), withTypeAssignableTo(type)); 
+3

您應該提及您正在使用Google Reflections。 – maba

1

與反思,我們可以做到這一點。

public static void main(String[] args) { 
    Method[] methodArr = Class1.class.getMethods(); 

    for (Method method : methodArr) { 
     if (method.getName().contains("get") && method.getAnnotation(JsonIgnore.class)==null) { 
      System.out.println(method.getName()); 
     } 
    } 
}