How to use Java generic methods to return different objects?

You can use Java generic methods to return objects of different types. Here is an example code:

public class GenericMethodExample {
    
    public static <T> T getObject(T obj) {
        return obj;
    }

    public static void main(String[] args) {
        String stringObj = getObject("Hello");
        Integer intObj = getObject(123);
        Double doubleObj = getObject(3.14);
        
        System.out.println(stringObj);
        System.out.println(intObj);
        System.out.println(doubleObj);
    }
}

In the example above, the getObject method is a generic method that utilizes a type parameter . It takes in a parameter and returns an object of the same type. In the main method, we passed a String, an Integer, and a Double object to the getObject method respectively, then assigned the returned objects to corresponding variables. Lastly, we printed the values of these variables.

This allows for the return of objects of different types through generic methods.

bannerAds