Skip to content
Advertisement

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;
}

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement