Generic type as parameter in Java Method
100,999
Solution 1
Yes, you can.
private static <T> List<T> pushBack(List<T> list, Class<T> typeKey) throws Exception {
list.add(typeKey.getConstructor().newInstance());
return list;
}
Usage example:
List<String> strings = new ArrayList<String>();
pushBack(strings, String.class);
Solution 2
Old question but I would imagine this is the preferred way of doing it in java8+
public <T> ArrayList<T> dynamicAdd(ArrayList<T> list, Supplier<T> supplier) {
list.add(supplier.get());
return list;
}
and it could be used like this:
AtomicInteger counter = ...;
ArrayList<Integer> list = ...;
dynamicAdd(list, counter::incrementAndGet);
this will add a number to the list, getting the value from AtomicInteger's incrementAndGet
method
Also possible to use constructors as method references like this: MyType::new
Solution 3
simple solution!
private <GenericType> ArrayList increaseSizeArray(ArrayList array_test, GenericType genericObject)
{
array_test.add(new genericObject());
return ArrayList;
}
Related videos on Youtube
Comments
-
Pierre Guilbert almost 2 years
Do you think it is possible to create something similar to this?
private ArrayList increaseSizeArray(ArrayList array_test, GenericClass) { array_test.add(new GenericObject()); // instance of GenericClass return array_test; }
-
Pierre Guilbert almost 13 yearsHow do you call that method? I don't know what Class<T> typekey should be. I can't find anything about it. If you have any reading advice, it will be welcome. Thank you for your response!
-
C. K. Young almost 13 years@Pierre: Just added a usage example. Basically, if you take a class name (
String
in this case) and add.class
after it, you have a type key (class object) for that class.String.class
has typeClass<String>
. -
Pierre Guilbert almost 13 yearsI just used it like this: static <T> List<T> pushBack(List<T> list, Class typeKey, int size) and it worked. Thank you, you helped me a lot. Avoiding copy/paste code is always a joy.
-
Deepak Gangore over 7 yearsWhy <T> is used just before return type ? I am also doing the same thing but i want to know the actual usage of <T>. Thanks in advance.
-
Douglas Held over 6 yearsdocs.oracle.com/javase/tutorial/extra/generics/methods.html introduces the construct of
static <T> void method(...)
-
Douglas Held over 6 yearsCorrection... docs.oracle.com/javase/tutorial/java/generics/methods.html actually introduces the syntax (the above link I provided does not).