Thursday, 12 September 2013

Dynamically calling a class method in java?

Dynamically calling a class method in java?

Is it possible to dynamically call a method on a class from java?
E.g, lets say I have the reference to a class, e.g either the string:
'com.foo.Bar', or com.foo.Bar.class, or anything else which is needed..).
And I have an array / list of strings, e.g [First, Last, Email].
I want to simply loop through this array, and call the method 'validate' +
element on the class that I have a reference to. E.g:
MyInterface item = //instantiate the com.foo.Bar class here somehow, I'm
not sure how.
item.validateFirst();
item.validateLast();
item.validateEmail();
I want the above lines of code to happen dynamically, so I can change the
reference to a different class, and the names in my string list can
change, but it will still call the validate + name method on whichever
class it has the reference to.
Is that possible?

No comments:

Post a Comment