I am trying to implement reflection code in java. I am new to using reflections and I have an existing method like this:
ScheduleParams incomeResetFXSchedule = performanceSwapLeg.getIncomeFxResetSchedule();
if (performanceSwapLeg.getIncomeFxResetSchedule().getDateRoll() != null) {
incomeResetFXSchedule.setDateRoll(DateRoll.valueOf(performanceSwapLeg.getIncomeFxResetSchedule().getDateRoll().toString()));
} else {
incomeResetFXSchedule.setDateRoll(DateRoll.valueOf(DateRoll.S_PRECEDING));
}
I was trying to write reflection code for the above code and I am stuck at this point:
try {
Class<ScheduleParams> incomeFXResetSchedule = ScheduleParams.class;
Class<DateRoll> dateRoll = DateRoll.class;
try {
Method m = PerformanceSwapLeg.class.getMethod("getIncomeFxResetSchedule");
m.invoke(performanceSwapLeg);
Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
m1.invoke(performanceSwapLeg);
} catch (Exception e) {
Log.error(CommonConstants.ERROR_LOG, "Failed to invoke the method" + e.getMessage());
}
} catch (Exception e) {
//Do Nothing
}
But I am not sure how to call the setter method and the getter method. Any suggestions on how to call this kind of methods using reflections.
You are already calling 'em! But just in the wrong way. When you do m.invoke
you're calling the method, but you're doing it like the following line:
getIncomeFxResetSchedule();
If you watch that line what you'll think? Uuuhm, I think I missed the variable where I'll save the value! Method.Invoke
returns an Object, thus you'll need to cast it to your class. I guess your class is ScheduleParams
.
ScheduleParams scheduleParams = (ScheduleParams) m.invoke(performanceSwapLeg);
Okay, great. Now I want to set it. Once again, you're calling a method which receives params without passing any param:
Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
m1.invoke(performanceSwapLeg);
It's like the following line:
setDateRoll();
That is probably throwing an
java.lang.IllegalArgumentException: wrong number of arguments
Because you have no method called like that which takes no arguments (I hope so), now the right way should be:
Method m1 = ScheduleParams.class.getMethod("setDateRoll", dateRoll);
m1.invoke(performanceSwapLeg, new DateRoll());
After that you could call the getter again and you'll get a whole new object.
I recommend you to read the following related question:
And the Oracle's documentation about reflection api.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.