Jigar Naik Jigar Naik - 7 months ago 23
Java Question

Is it possible to make method generic without making class generic to return List<T>

Is it possible to make a method Generic without making class generic ?
Is there anyway to achieve below using generic type?

The code below does not compile, this is just to show what I want to achieve.

public class Test {

public List<T> execute(String name, Map<String, Object> params, List<T> type) {
List<Object> emps = new ArrayList<Object>();
emps.add(new Employee());
//emps object will be generated dynamically
return (List<T>)emps;
}

public static void main(String[] args) {
Test test = new Test();
test.execute("testing", null, new ArrayList<Employee>());
}
}

Answer

Try this:

public <T> List<T> execute(String name, Map<String, Object> params, List<T> type) {
    List<Object> emps = new ArrayList<Object>();
    emps.add(new Employee());
    //emps object will be generated dynamically
    return (List<T>) emps;
}

Have a look at this explanation:

The Java compiler takes advantage of target typing to infer the type parameters of a generic method invocation. The target type of an expression is the data type that the Java compiler expects depending on where the expression appears. Consider the method Collections.emptyList, which is declared as follows:

static <T> List<T> emptyList(); Consider the following assignment statement:

List<String> listOne = Collections.emptyList(); This statement is expecting an instance of List<String>; this data type is the target type. Because the method emptyList returns a value of type List<T>, the compiler infers that the type argument T must be the value String. This works in both Java SE 7 and 8. Alternatively, you could use a type witness and specify the value of T as follows:

List<String> listOne = Collections.<String>emptyList();

https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html

Comments