Below is my code from which I am using reflection to call a method but I am always getting exception
List<PdAttrKey> attrKeys = new ArrayList<PdAttrKey>();
Properties adapterProps = new Properties();
PdReadRequest pdReadRequest = new PdReadRequest(1L, 1L, (short) 0, new Date(),
dataDurationSec, 2L, 3L, attrKeys, null, adapterProps);
PdAdapterUserReadOnlyGemsReader adapter1 = new PdAdapterUserReadOnlyGemsReader();
PdReader reader = adapter1.acquireReader(pdReadRequest);
UserCacheDoImpl userDos = Some Value;
Method method = getClassMethod("createPdRecordFromUserDO");
// This line is throwing me exception. And I don't know why?
PdRecord onePdsxRecord = (PdRecord) method.invoke(reader, userDos);
This is the below method from which I am getting all the method names of a class.
private Method getClassMethod(String methodName) {
Method method = null;
Method[] methodList = PdAdapterUserReadOnlyGemsReader.PdUserReadOnlyGemsReader.class
.getDeclaredMethods();
for (Method m : methodList) {
if (m.getName().equals(methodName)) {
method = m;
method.setAccessible(true);
break;
}
}
return method;
}
Some More Code:-
private PdRecord createPdRecordFromUserDO(UserCacheDoImpl userCache) {
// Some code here
}
This is the exception I am getting. Any idea why?
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
Any suggestions will be of great help.
If we want to catch the IllegalArgumentException then we can use try-catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping.
You passed an argument of one type that could not be coerced to the type expected. For example, this error occurs if you try to pass an Integer variable when a Long is expected. If you want coercion to occur, even if it causes information to be lost, you can pass the argument in its own set of parentheses.
Please check if more than one method with name "createPdRecordFromUserDO" exists. It looks like there are more than one, but with different arguments.
Your method getClassMethod returns the first method it finds, but that could be the wrong one. Check if methodList.length > 1, then this is the cause of the bug.
Rethink what you want to do if multiple methods with the given name are found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With