Morteza Malvandi
Morteza Malvandi

Reputation: 1724

How get public methods of a java class and then run it?

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?

Upvotes: 0

Views: 848

Answers (2)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

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

Upvotes: 3

Masudul
Masudul

Reputation: 21961

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

Upvotes: 2

Related Questions