Donatello
Donatello

Reputation: 353

How to work with generics and Class<T> class in java

I have my custom public class Example in the package com.classes.

1. How can I get Class<Example> intance1 and Class<Example[]> instance2?

I can use Class classInstance = Class.forName("com.classes.Example");

But In this case I recieve raw type Class.

2. Is it impossible to create Class<Example[]> from Class<Example> instance, right?

Upvotes: 0

Views: 50

Answers (1)

rgettman
rgettman

Reputation: 178263

For your first question, use a class literal, which is the class name followed by .class.

Class<Example> c = Example.class;

For your second question, I don't see any method in the Class class of retrieving the Class object for the array of the same type, e.g. no way to get a Class<Example[]> from a Class<Example>. But you can still use a class literal to get it directly.

Class<Example[]> c = Example[].class;

However, it appears that you can get the Class object for the component type of the class representing an array, i.e. the reverse of what you want, but it returns a Class<?>.

Class<?> c = Example[].class.getComponentType();

Upvotes: 4

Related Questions