3

I have a class with some methods in Java as follows:

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;
    }
}

I want to get all methods in Class1 that start with the String get which are not declared with the @JsonIgnore annotation.

How do I do this?

whirlwin
  • 16,044
  • 17
  • 67
  • 98
Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73
  • You will get some idea from this : http://stackoverflow.com/questions/6593597/java-seek-a-method-with-specific-annotation-and-its-annotation-element – RahulArackal Apr 23 '15 at 08:33
  • I'm guessing you are trying to convert the java class to json. Try this library http://flexjson.sourceforge.net/ . It handles multiple levels, custom transformations and include/exclude paths. – Goose Apr 23 '15 at 08:39

3 Answers3

4

You can use Java Reflection to iterate over all public and private methods:

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());
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

You can use java reflections. Eg.

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));
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
1

With Reflection we can achieve this.

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());
        }
    }
}
Alok Pathak
  • 875
  • 1
  • 8
  • 20