Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a generic class to a method in Java?

Suppose we have a function that creates objects given a particular class:

public static <T> T createObject(Class<T> generic) {
    try {
        return generic.newInstance();
    } catch (Exception ex) {
        return null;
    }
}

We can use the function easily to create instances of non-generic types.

public static void main(String[] args) {
    Foo x = createObject(Foo.class);
}

Is it possible to do the same thing with a generic type?

public static void main(String[] args) {
    ArrayList<Foo> x = createObject(ArrayList<Foo>.class); // compiler error
}
like image 243
Anton Avatar asked Apr 16 '11 00:04

Anton


People also ask

Can we inherit generic class in Java?

It inherits all members defined by super-class and adds its own, unique elements. These uses extends as a keyword to do so. Sometimes generic class acts like super-class or subclass. In Generic Hierarchy, All sub-classes move up any of the parameter types that are essential by super-class of generic in the hierarchy.

Can a non generic class have a generic method?

Yes, you can define a generic method in a non-generic class in Java.


2 Answers

Generics, in Java, are implemented through type erasure.

That means that an ArrayList<T>, at run time, is an ArrayList. The compiler simply inserts casts for you.

You can test this with the following:

ArrayList<Integer> first = new ArrayList<Integer>();
ArrayList<Float> second = new ArrayList<Float>();

if(first.getClass() == second.getClass())
{
    // should step in the if
}
like image 178
Etienne de Martel Avatar answered Oct 24 '22 22:10

Etienne de Martel


Also, as long as you are sure of what you are doing, and as long as you are pretty sure your code cannot incur heap pollution you can suppress the warning.

You may also take into consideration that your code cannot instantiate arrays, which by chance also requires an unchecked exception:

@SuppressWarnings("unchecked")
public static <T> T[] createArray(Class<T> anyClass, int size){
    T[]result = null;
    try{
        result = (T[]) Array.newInstance(anyClass, size);
    }catch(Exception e){
        e.printStackTrace();
    }
    return result;
}

This is how I used it:

public static void main(String[] args) throws Exception{
    @SuppressWarnings("unchecked")
    List<String> jediNames = (List<String>) createObject(ArrayList.class);
    jediNames.add("Obiwan");

    String[] moreJedis = createArray(String.class, 10);
    System.out.println(moreJedis.length);
    moreJedis[0] = "Anakin";
}
like image 43
Edwin Dalorzo Avatar answered Oct 24 '22 22:10

Edwin Dalorzo