Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

reflection - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...