How to get a special method of a class in java?

I have a class with some methods in Java like this:

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 String get

that are not annotated @JsonIgnore

.

How to do it?

+3


source to share


3 answers


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

      

+4


source


You can use java reflections. For example.



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

      

+2


source


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

      

+1


source







All Articles