Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java dynamic function calling

I have a String array that contains names of method in the yyyyyy class

In the xxxxxx class I'm making a yyyyyy instance (say obj). Now I can call obj.function_name(), except I want to read function_name from the String array in a loop. Is this possible?

like image 304
dpaksp Avatar asked Jun 16 '10 05:06

dpaksp


People also ask

How do you call a method dynamically?

Using user data to call any method via send could leave room open for users to execute any method they want. send is often used to call method names dynamically—but make sure the input values are trusted and can't be manipulated by users. Golden rule is never trust any input that comes from the user.

What is dynamic function in Java?

Dynamic method dispatch is the mechanism in which a call to an overridden method is resolved at run time instead of compile time. This is an important concept because of how Java implements run-time polymorphism.


1 Answers

You can, using reflection. It is done by calling Yyyy.class.getMethod("methodName").invoke(someArgs)

You'd have to handle a bunch of exceptions, and your method must be public. Note that java coding conventions prefer methodName to method_name.

Using reflection, however, should be a last resort. You should be using more object-oriented techniques.

If you constantly need similar features, perhaps you can look at some dynamic language running on the java platform, like Groovy

like image 108
Bozho Avatar answered Oct 04 '22 18:10

Bozho