2

Is there any way to use reflection to create an instance of a generic class.

For example, how to create an instance of PriorityQueue<Integer> using reflection such as Class or Type, instead of call its constructor.

1
  • 2
    Yes, you just create a raw instance of the class, and cast it. There is no difference between the two, owing to type erasure. Commented Feb 2, 2017 at 20:29

1 Answer 1

2

You can always cast raw types to/from generic types.

PriorityQueue<Integer> queue = (PriorityQueue<Integer>) PriorityQueue.class.newInstance(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.