Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Pass .class Reference

Tags:

java

generics

I need to call a super constructor that requires me to pass a .class reference of a generic type. How can I achieve this with Java?

The constructor wants to have..

Class<List<MyType>>

As generics are erased at runtime, I have no clue how to satisfy the constructor.

List<MyType>.class // does not work ;-)
like image 946
chris1069603 Avatar asked Aug 21 '12 08:08

chris1069603


People also ask

How do you pass a generic object in Java?

We use generics wildcard (?) with super keyword and lower bound class to achieve this. We can pass lower bound or any supertype of lower bound as an argument, in this case, java compiler allows to add lower bound object types to the list.

How do you make a class generic in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.

How do you declare a generic type in a class explain?

If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section.


2 Answers

Like this (cast to the Class raw type first):

@SuppressWarnings({ "unchecked", "rawtypes" })
Class<List<MyType>> clazz = (Class) List.class
like image 198
Lukas Eder Avatar answered Oct 16 '22 15:10

Lukas Eder


You can't call the constructor for List<MyType>, in fact you can't call the constructor for List as its an interface. What you can do is call the constructor for ArrayList.class and also pass the type of the elements you expect.

public C createCollection(Class<? extends Collection> collectionClass, Class elementClass, int number) {
    Collecton c = (Collection) collectionClass.newInstance();
    for(int i=0;i<number;i++)
       c.add(elementClass.newInstance());
    return (C) c;
}

List<MyType> list = createCollection(ArrayList.class, MyType.class, 100);
like image 40
Peter Lawrey Avatar answered Oct 16 '22 15:10

Peter Lawrey