Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get special method of class in java?

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?

like image 788
Morteza Malvandi Avatar asked Dec 02 '25 06:12

Morteza Malvandi


1 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());
    }
}
like image 164
Tim Biegeleisen Avatar answered Dec 03 '25 20:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!