Wouter Oet wrote:There are a couple of things weird about your code:
You're not using generics. And probably your problem is that you are iterating over the HashMap size and not over the
descriptors size. And why do you copy all the values into a new array except for the class entries? Why not just skip them?
Paul Clapham wrote:The reason? When you called the invoke() method, an error was thrown. Perhaps by the method you were invoking? You don't know because you didn't...
What can be done about it?
Look at the stack trace to see what the error was. Not only will there be a stack trace for the InvocationTargetException, there will also be a stack trace for the actual exception which was thrown by the invoked method.
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Rob Prime wrote:
Your first argument is a Class object, but it needs to be an instance of the class represented by the Class object. For example, if clazz == String.class you would need to pass a String.
Rob Prime wrote:It depends. If it's ok to call the method on a new instance that isn't referred to from anywhere else, then that code should work. If you need to call the method on an existing instance then you'll need to pass that instance to the method. Something tells me that's the case.
I'd change your method signature slightly:
You will now be setting the values to an existing object.
Rob Prime wrote:You no longer should pass the Class object as your first argument but an instance of that class - the instance whose fields you want to set.
Rob Prime wrote:
Rob Prime wrote:Why do you create a new Object to pass into writeMethod.invoke? Why not use the argument to the method, as I've shown before?
Rob Prime wrote:I see two possible improvements:
- use Map<String,String> instead of HashMap<String,String> in the method signature to allow TreeMap as well.
- check if the method's parameter list expects only one String or Object:
This will prevent issues where the property is not a String property but for instance an Integer.