Tattat
Tattat

Reputation: 15778

Can I make the method dynamically called in Java?

for example, I have a variable called ("method"), it is a String, but I would like to do something like this....

obj.method(); //The object called the method();

But I would like to change the .method to a dynamic method, which means, I want to call the method base on the variable. For example, if I the I do something like this:

method = ".toString()";

Is there any method to help me to pass this string to the object, and the object will call the

obj.toString();

If the method is

method = ".toChar()";

I want it called the

obj.toChar();

How can I do so? Thank you.

Upvotes: 0

Views: 106

Answers (2)

musiKk
musiKk

Reputation: 15189

You use the reflection API for this. In your case it would be something like this:

String method = "toString";
Class<Obj> objClass = obj.getClass();
Method m = objClass.getMethod(method);
m.invoke(obj);

It's untested but it should work. Otherwise just read a bit around in the documentation.

Note that this is often (but not always) the wrong way to do things in Java.

Upvotes: 5

Gopi
Gopi

Reputation: 10293

Reflection is the way. Here is a starting point for you.

You may refer a tutorial here.

Upvotes: 0

Related Questions