This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Reflection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reflection" Watch "Reflection" New topic
Author

Reflection

Stephen Murphy
Greenhorn

Joined: Feb 26, 2004
Posts: 24
Hello
I am learning to use reflection for the first time, and I am having some trouble understanding hte concept. What I need to do for the project I am working on, is take information about a class(name, method name, params) from an XML file, and the reflect the proper method. I understand how to instantiate a class, but it just gets fuzzy from there. THis is what I have so far:



componentName and the result of getComponentMethod() are both strings. getParams() returns an array of 2 strings.

The params may be anything though when I parse the XML file. Any number of parameters of any type in any order.

Thank you for your help.
Tim LeMaster
Ranch Hand

Joined: Aug 31, 2006
Posts: 226
In the call to getMethod(String methodName, Class[] parameterTypes). You need to pass in an array of Class objects, that match the methods parameter types in order.

So for a method with 2 strings you would need to pass in

getMethod("methodName", new Class[] {java.lang.String.class, java.lang.String.class});

Of course for this to be truly flexible you would need to get the type from the XML file. Try to find a class by this name. Pass these classes as an array to the getMethod call. Then try to turn the values in the XML value into an instance of their type. Then pass an Object[] of them into the invoke call.
Stephen Murphy
Greenhorn

Joined: Feb 26, 2004
Posts: 24
Thanks for the reply.
I have figured out my problem, and now have a new one.


When i get to the Class.forName() call, I get a class not found exception even though the class I am looking for exists and is in the same package.
Any idea why this would happen?

Thanks,
Stephen
 
 
subject: Reflection