File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reflection" Watch "Reflection" New topic


Stephen Murphy

Joined: Feb 26, 2004
Posts: 24
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

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?

I agree. Here's the link:
subject: Reflection
It's not a secret anymore!