Can I use a string variable as a data type to create other variables in java

I use reflection to call a method like:

method.invoke(someObject, null);

The problem is that I want to use the value returned by this method, without this data type being known in advance. I know the data type in a string variable, let's say

String type = "String";

Is it possible to do something equivalent to this -

type variable = method.invoke(someObject, null)
+4
source share
2 answers

Check the type of object with instanceof.

Object o = method.invoke(...);
if(o instanceof Integer) {
    // Integer logic...
}
if(o instanceof YourType) {
    // YourType logic...
}
// and so on
+1
source

Maybe something like this might work for you:

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

But I recommend not to follow this road. There must be some better way to achieve the desired result.

0
source

Source: https://habr.com/ru/post/1589238/


All Articles