5/23/2011

Java Reflection API in Liferay

I am currently experimenting with the Java Reflection API in combination with Liferay and the Dynamic Query API. I want to see if I can build some more generic accessor classes for the Dynamic Query API. So I started today and I came across this Exception:

Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)


This happens, when you (like me) try to invoke a method without providing an actual instance of the class the method should be invoked on. So don´t use


Method method = instanze.getClass().getMethod("getTest", (Class[]) null);
Object[] myArray = new T1[0];
method.invoke(myArray);


Use instead

method.invoke(instanze,myArray);


If you like this post it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.