bitma
bitma

Reputation: 137

use variable as object name to call the object method

I have a class which contains a couple different objects.

I can use getDeclaredFields to get the name list of all objects, but I want to call a method in these objects.
How can I do that?

ClassA a = new ClassA();
Class cls = c.getClass();
Field[] fields = cls.getDeclaredFields();
for(int i = 0; i< fields.length;i++) {
   System.out.println("Field = " + fields[i].toString());
   System.out.prontln(fields[i].method()) // how can I call the method from object fields[i]             
}

more info: the reason I use reflection is I want write a test class which can be used to test all other classes' objects are properly existing.

testclass(class a), get all objects name in the class a, and use object.exists() method to verify the existing of this object.

here is my code: I have some dialog classes, each dialog class has some menuitem class, checkbox class,textfield class, I want write a class which can be used to verify all checboxes,textfields are exsting (use checkbox.exist(), textfield.exist() ...) in the given dialog.

ToolsMenu c = new ToolsMenu();
        Class cls = c.getClass();
        Field[] fields = cls.getDeclaredFields();
        for(int i = 0; i< fields.length;i++) {
            System.out.println("Field = " + fields[i].toString());
            println( fields[i].getDeclaringClass().exists()

I can use getdeclaringclass to get the field[i] class, but how can i call method exists() which is defined in checkboxes,textfields class.

Upvotes: 1

Views: 1243

Answers (2)

Ondrej Bozek
Ondrej Bozek

Reputation: 11481

You can call it with something like this:

...
Class clazz= fields[i].get(c).getClass();
clazz.getMethod("methodName").invoke(fields[i].get(c));
...

Where "methodName" is name of the method which should be called. You can also pass some parameters to the method.

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83527

I'm not sure why you are using reflection at all. You can simply do

a.field.method()

If field and its method() declare the correct access modifiers.

Upvotes: 2

Related Questions