~/ learn/ comp-308/ cards/ Type erasure & its consequences
1 of 5

Type the Class<T> factory that replaces new T()

Type the Class<T> factory that replaces new T()

Answer

static <T> T create(Class<T> type) throws Exception { return type.getDeclaredConstructor().newInstance(); }

Because new T() is impossible under erasure, you pass the Class<T> token. It survives erasure as an ordinary object, so newInstance() has the runtime type that the bare type parameter lacks. This is the standard workaround.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/96c52b3f-6ceb-4c51-8d75-96ab8087d04e/flashcard utf-8 LF