I am trying to execute methods of a class using reflection, the method accepts a map of methodNames & list of arguments the method needs. One such method is setPaperSize(int x)
. Now the problem is at the //error line, x.getClass()
returns Integer not int, and due to that I end up with NoSuchMethodException
. I know this returns runtime class of variables, Any workarounds or solutions to make it work?
private void applyProps(HTML2PDF converter, Map<String, Object> propValues) {
propValues.keySet().forEach(k -> {
Method methodToExecute;
try {
Object argObj = propValues.get(k);
List<Object> args = null;
if(argObj instanceof List) {
args = (List<Object>)argObj;
}else {
args = new ArrayList<Object>();
args.add(argObj);
}
//error line
List<Class<?>> argsClass = args.stream().map(x -> x.getClass()).collect(Collectors.toList());
methodToExecute = HTML2PDF.class.getMethod(k, argsClass.toArray(new Class[argsClass.size()]));
methodToExecute.invoke(converter, args);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException("Error in invoking the reflection method", e);
}
});
}
Aucun commentaire:
Enregistrer un commentaire