问题描述:

I use reflection to invoke a method as:

method.invoke(someObject, null);

The problem is, I want to use the value that this method returns without having it's data type known before hand. I have the knowledge of the data type in a string variable, say

String type = "String";

Is it possible to do something equivalent of this-

type variable = method.invoke(someObject, null)

网友答案:

Check the Object type with instanceof.

Object o = method.invoke(...);
if(o instanceof Integer) {
    // Integer logic...
}
if(o instanceof YourType) {
    // YourType logic...
}
// and so on
网友答案:

Maybe something like this could work for you:

if(type.equals("String"){
    String o = (String) returnedObject;
} else if(type.equals("Integer")){
    Integer o = (Integer) returnedObject;
}

But I recommend not going down this road. There has to be some better way to achieve your desired result.

相关阅读:
Top