How To Instantiate a java.util.ArrayList with Generic Class Using Reflection? I am writing a method that sets java.util.List on target object. A target object and a generic
Generics are a compile-time only "trick".
Reflection is runtime-only.
Basically, you can't - you can only create a "raw" ArrayList
. If you need to pass it into methods that take generic parameters, casting it directly after construction will be safe (regardless of the "unchecked" warning). In this example, there's no compile-time type safety anyway due to using general Objects
, so no casting is needed.