Shamik
Shamik

Reputation: 1731

java reflection question

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

Upvotes: 2

Views: 433

Answers (1)

Chris Thompson
Chris Thompson

Reputation: 35598

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.

Upvotes: 3

Related Questions