当前位置: 动力学知识库 > 问答 > 编程问答 >

reflection - Can i use a string variable as a datatype to create other variables in java

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: