views:

48

answers:

1

Hi, I'm trying to solve the following issue in reflection. I've a POJO which kind of acts as a metadata for the method signature in TestResponse class. TestResponse has a setDate() methid which takes a Date parameter. I'm trying to make this is a generic code which can accept any method and its signature to set in the response. What I'm not able to figure out is how to set the parameter Class while calling getMethod() based on the input. The input tells me to set the parameter as Date, but not sure how to achiever that.

Here's my sample code. Ofcourse, the mdi.modifier.getClass() is wrong since it'll get String.class instead of Date.class.

TestResponse response = new TestResponse();
Object val = "test";
MDIBase mdi = new MDIBase("setDate", "Date");
Method m = response.getClass().getMethod(mdi.method, mdi.modifier.getClass());
m.invoke(response, new Object[] { val });

Here's MDIBase

public class MDIBase {
public String method;
public String modifier;
public MDIBase(String method, String modifier){
this.method = method;
this.modifier = modifier;
}

Any pointers will be highly appreciated.

Thanks

+3  A: 

I'm not sure I fully understand you, but if I do, you want to be able to pass in a class name for the parameter?

In order to do that, instead of passing in "Date" pass in "java.util.Date" (this is known as the fully qualified class name) and then instead of getClass call

response.getClass().getMethod(mdi.method, Class.forName(mdi.modifier));

That will dynamically load the class that has the fully qualified name you supplied.

Is that what you're looking for? If not, give me some more information and I'll take another stab at it.

Chris Thompson
Exactly what I was writing! But also, why use a String for mdi.modifier? Why not make it a Class object? Then your line `MDIBase mdi = new MDIBase("setDate", "Date");` would be `MDIBase mdi = new MDIBase("setDate", java.util.Date.class);`
Stephen P
@Stephen, that could totally work. I just was attempting to be as close to what @Shamik's original code was :-). I would think that the string might allow for more flexibility in the instance where you wanted the user to be able to specify the class name (like from the command line or xml, etc.)...but it would definitely work all the same...
Chris Thompson
Perfect, this is exactly what I was looking.. thanks a ton Chris, appreciate your help.
Shamik
Thanks a lot for looking into this Stephen ..
Shamik
@Chris - I completely agree, and use Strings myself e.g. in a Properties file which configures `permission_name=com.example.ClassThatImplementsThePermission` My thought being If you're going to hard-code *"Date"* it's better to hard-code *java.util.Date.class*
Stephen P
@Stephen, totally see your point and agree!
Chris Thompson