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.
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.
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