0

I have a java class. I want get all methods of this class that are public and defined in the class. My code is as follows:

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


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

    public void setB(String b){
        this.b = b;
    }

    public String getA(){
        return a;
   }

    private String getB(){
        return b;
    }
}

I want Only to get setA, setB, and getA and then run this methods.

How do I do?

Arun Xavier
  • 763
  • 8
  • 47
Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73

2 Answers2

3

You should take a look at invoke() with reflection.

Class1 class1=new Class1();
Method[] methods=class1.getClass().getDeclaredMethods();
for(Method i:methods){
   if (Modifier.isPublic(i.getModifiers())) {
     try {
       i.invoke(class1, "a");
     } catch (IllegalAccessException | InvocationTargetException e) {
       e.printStackTrace();
     }
  }
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

Get all accessible public methods using getMethods, it will include all methods of Object class also, than you can only view Class1 public methods by checking getDeclaringClass()

 Class c = Class1.class;
 Method[] pubMeth = c.getMethods();
 for(Method m : pubMeth){
    if(m.getDeclaringClass() == c){ // Only Class1 pub methods
      System.out.println(m.getName());
    }
 }
Masudul
  • 21,823
  • 5
  • 43
  • 58