How To Instantiate a java.util.ArrayList with Generic Class Using Reflection

后端 未结 6 1291
野的像风
野的像风 2020-12-10 13:37

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

6条回答
  •  离开以前
    2020-12-10 14:26

    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.

提交回复
热议问题