misko herko
misko herko

Reputation:

Class object of generic class (java)

is there a way in java to get an instance of something like Class<List<Object>> ?

Upvotes: 63

Views: 60424

Answers (7)

Lorcan O&#39;Neill
Lorcan O&#39;Neill

Reputation: 3403

You could use Jackson's ObjectMapper

ObjectMapper objectMapper = new ObjectMapper();
CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, ElementClass.class)

No unchecked warnings, no empty List instances floating around.

Upvotes: 2

Armhart
Armhart

Reputation: 361

public final class ClassUtil {
    @SuppressWarnings("unchecked")
    public static <T> Class<T> castClass(Class<?> aClass) {
        return (Class<T>)aClass;
    }
}

Now you call:

Class<List<Object>> clazz = ClassUtil.<List<Object>>castClass(List.class);

Upvotes: 36

Yishai
Yishai

Reputation: 91931

Because of type erasure, at the Class level, all List interfaces are the same. They are only different at compile time. So you can have Class<List> as a type, where List.class is of that type, but you can't get more specific than that because they aren't seperate classes, just type declarations that are erased by the compiler into explicit casts.

Upvotes: 10

newacct
newacct

Reputation: 122538

how about

(Class<List<Object>>)(Class<?>)List.class

Upvotes: 79

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

As mentioned in other answers, Class represents an erased type. To represent something like ArrayList<Object>, you want a Type. An easy way of getting that is:

new ArrayList<Object>() {}.getClass().getGenericSuperclass()

The generic type APIs introduced in 1.5 are relatively easy to find your way around.

Upvotes: 6

Jason S
Jason S

Reputation: 189906

List.class

the specific type of generics is "erased" at compile time.

Upvotes: 0

jwoolard
jwoolard

Reputation: 6294

You can get a class object for the List type using:

Class.forName("java.util.List")

or

List.class

But because java generics are implemented using erasures you cannot get a specialised object for each specific class.

Upvotes: 0

Related Questions