How do I use generics with an array of Classes?

It seems a bit defeatist, but problems like this are precisely the reason why most people avoid mixing arrays and generics. Because of the way generics are implemented (type erasure), arrays and generics will never work well together.

Two workarounds:

  • Stick to using a collection (e.g. ArrayList<Class<? extends SuperClass>>), which works just as well as an array and also allows expansion.
  • Put a @SuppressWarnings("unchecked") annotation on the code creating the array along with a comment justifying its use.

Leave a Comment