Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type as parameter in Java Method

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; } 
like image 869
Pierre Guilbert Avatar asked Jul 20 '11 16:07

Pierre Guilbert


People also ask

What is a generic type parameter in Java?

A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

How do you provide a generic parameterized type?

In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.

What is generic type in Java example?

Java Generic Type Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.) K - Key (Used in Map)


1 Answers

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); 
like image 188
Chris Jester-Young Avatar answered Sep 21 '22 15:09

Chris Jester-Young