Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Parameter Type and Return Type in Java

Tags:

java

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);
        }
    }
}
like image 452
Purus Avatar asked May 19 '16 16:05

Purus


1 Answers

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.

like image 187
John Bollinger Avatar answered Sep 27 '22 18:09

John Bollinger