开发者

Getting a JavaExecutionException on my invoke method?

I'm trying to invoke a method by means of reflection. The signature of the method I'm trying to get is as follows:

public static JPAQuery find(String query, Object... params) {...}

I used the following snippet to get the declared method:

Method findEntities = clazz.getDeclaredMethod("find", params);

I'm trying to invoke with the following snippet:

Object[] args = new Object[2];
args[0] = fieldName + " = ?"; // Of type String
args[1] = entity; // Of a type extending GenericModel
JPAQuery query = (JPAQuery)findEntities.invoke(null, args); <-- EXCEPTION HERE!!!

...but getting the following exceptions:

play.exceptions.JavaExecutionException: argument type mismatch
....
Caused by: java.lang.IllegalArgumentException: argument type mismatch

and

play.exceptions.JavaExecutionException: wrong number of arguments
...
Caused by:开发者_开发问答 java.lang.IllegalArgumentException: wrong number of arguments

Can anyone help with this?

Further Observation

When I change the line:

JPAQuery query = (JPAQuery)findEntities.invoke(null, args);

to

JPAQuery query = (JPAQuery)findEntities.invoke(null, fieldName, entity);

one of the exception stating "wrong number of arguments" disappear. So I only have the argument type mismatch issue now. Almost there... :D


public static JPAQuery find(String query, Object... params)

That vararg parameter is just a pretty syntax for Object[] params.

So you need to pass in two parameters, the String, and an Object array with your entity.

JPAQuery query = (JPAQuery)findEntities.invoke(
     null, fieldName, new Object[]{ entity} );


findEntities.invoke(null, args); 

Here the first parameter should be the object the method is invoked from. You pass null, so it can´t work.

For further information see the documentation: http://download.oracle.com/javase/1,5.0/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29

Additionally I would chance the line:

Method findEntities = clazz.getDeclaredMethod("find", params);

To

Object[] params = new Object[1];
params[0] = Object.class;
Method findEntities = clazz.getDeclaredMethod("find", params);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜