开发者

Problem with Method.invoke

I have a method that return a list of objects and I want to call it by the invoke method of the class Method. The only problem is that invoke method returns an Object and not a list<Object>.

The code is here:

Class<? extends开发者_如何学JAVA AnObject> anObject = MyObject.getClass();
Method myMethod = MyObject.getMethod("getListObject"); 
Object objject = method.invoke(MyObject); // I want it to return list

How can I solve it?


Class<? extends AnObject>  anObject = MyObject.getClass();
Method myMethod = MyObject.getMethod("getListObject"); 
List object = (List)myMethod.invoke(anObject);


Just typecast it:

List list = (List)method.invoke(...);


You can explicitly cast the result to the type you desire.

List<?> theList = (List<?>) method.invoke(anObject, new Object[] {})

This may result in a ClassCastException in runtime if the method doesn't return the type you expected.


How about letting dp4j's annotations processor figure it out?

@com.dp4j.Reflect //or @org.junit.Test
public void test(){
  Object objject =  MyObject.getListObject();
}

You can also print the injected code with -Averbose=true.


what let me to this page is

when I tried to invoke a protected method without making it Accessible

take look at my now working version

DoPubService service = SpringAdapter.getBean("frontendDoPubService", DoPubService.class);
try {
    Method runUrlReplacerMethod = service.getClass().getDeclaredMethod("runUrlReplacer", String.class, String.class, String.class);

    return runUrlReplacerMethod.invoke(service, "10.21019/qna-900031", "abs", explanation);
 } catch (Exception e) {
    e.printStackTrace();
}

this is not working because the Method should be Accessible before invoking it

runUrlReplacerMethod.setAccessible(true);


Java 8 solution:

List<?> list = (List) invokeResult;
List<String> = list.stream().map(el -> (String) el).collect(Collectors.toList());

Change String to type you need.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜