I am trying to create a Java method which accept a Object type and the type of data type it should be converted to.
For example if I should be able to return a value of 1 as Int or Double as required. I am using Class to pass the data type as parameter.
Question: How can I make the method generic to accept return type based on the input parameter?
The below code is just an example and it may be syntactically incorrect and provided to explain my question.
public class JavaTest {
public static void main(String[] args) {
getValue(1,int.class);
getValue(1,double.class);
getValue("adf",String.class);
}
public static <E> void getValue(Object obj,Class<?> type) {
if (type == String.class) {
// return string value
}else if (type == int.class) {
//return Integer.parseInt(obj);
}else if (type == double.class) {
//return Double.parseDouble(obj);
}
}
}
How can I make the method generic to accept return type based on the input parameter?
The type parameter can be used to designate the method's return type, and you can associate that with the Class
argument by means of that argument's type parameter:
public static <E> E getValue(Object obj, Class<E> type) {
You will also need to use Class.cast()
to satisfy the compiler that the method returns the correct type. (You could also use an ordinary cast, but that will be subject to type safety warnings.) For example:
// ...
} else if (type == Integer.class) {
return type.cast(Integer.valueOf(obj.toString()));
}
Note also that you cannot this way effect conversions directly to primitive types, as your code suggests you are trying to do. You must instead convert to their wrapper classes. In other words, you cannot use int.class
, double.class
, etc.; you must instead use Integer.class
, Double.class
, and so forth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With