Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- Using generics to return more than one type

I have a method like this-

public List<Apples> returnFruits(String arg1){
List<Apples> fruits = new ArrayList<Apples>();
Apple a = new Apple();
fruits.add(a);

return fruits;
}

I would like to change it, so that I can specify the fruit type from the method call and return that fruit list. So the 2nd statement should dynamically instantiate the list of fruits that I pass. I thought of this-

public List<?> returnFruits(String arg1){
List<T> fruits = new ArrayList<T>();
T t = new T();
fruits.add(t);

return fruits;
}

But don't know the right way to do it, as you can see.

In the second method, I just return the fruit instead of the list-

public T returnFruit(){
T t = new T();
return t;
}

The fruits that are passed are NOT in the same class hierarchy and are different types.

Thank you.

like image 599
codebee Avatar asked Jul 05 '26 22:07

codebee


1 Answers

If you know for sure that you'll have a no argument constructor, you could use this syntax :

public <T> List<T> returnFruits(Class<T> clazz){
    List<T> fruits = new ArrayList<T>();
    T t = clazz.newInstance();
    fruits.add(t);

    return fruits;
}

Usage :

List<MyClass> m = returnFruits(MyClass.class, "plop");

If you know you have a constructor with a String parameter :

public <T> List<T> returnFruits(Class<T> clazz, String arg1){
    List<T> fruits = new ArrayList<T>();
    Constructor<T> constructor = clazz.getConstructor(String.class);
    T t = constructor.newInstance(arg1);
    fruits.add(t);

    return fruits;
}

Usage :

List<MyClass> m = returnFruits(MyClass.class, "plop");

Etc.

like image 101
Nicocube Avatar answered Jul 08 '26 12:07

Nicocube