4

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)
6
  • 2
    What exactly are you trying to achieve? Why not just return it to an Object? Commented May 21, 2015 at 14:57
  • I want to do type specific operation. For e.g. if it was an integer, I will check if it is less than 0. How will I achieve this if it is just of Object data type? Commented May 21, 2015 at 15:00
  • What about myObject.equals(Integer.valueOf(0)) ? Commented May 21, 2015 at 15:04
  • You must know something about the object coming in or else how do you know what method to invoke via reflection? Commented May 21, 2015 at 15:18
  • I believe this question has already been asked here: stackoverflow.com/questions/12286871/… Commented May 21, 2015 at 15:39

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Any non if way to do it?
0

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.

1 Comment

I also feel the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.