How can I return type Object from a method to an unknown type without causing a type mismatch?
How can I return type Object from a method to an unknown type without
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could use Generics to infer the return type, like this:
Note that you need to ensure you can cast to inferred type, so you might want to pass
Class<T>as a parameter, in order to check the type ofT.Inferring the type of
Tjust from the assignment might be helpful if you’re actually returning a generic object whose generic parameter isT. Have a look atCollections.emptyList()for example, which returns an emptyList<T>(so there aren’t any elements in the list that are not of typeT).You could also set bounds for the
Ttype: