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

后端 未结 6 1292
野的像风
野的像风 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:06

    Generics only work at compile time, therefore if you're using reflection, they won't be available.

    See more about this here.

    0 讨论(0)
  • 2020-12-10 14:06

    An object doesn't know about its generic type at execution time. Just create a new instance of the raw type (java.util.ArrayList). The target object won't know the difference (because there isn't any difference).

    0 讨论(0)
  • 2020-12-10 14:17

    There's no need to do any reflection for creating your List. Just pass in some additional type information (usually done by passing a class of the correct type).

    public static <T> List<T> createListOfType(Class<T> type) {
        return new ArrayList<T>();
    }
    

    Now you have a list of the required type you can presumably/hopefully set it directly on your targetObject without any reflection.

    0 讨论(0)
  • 2020-12-10 14:25

    An object doesn't know about its generic type at execution time. Just create a new instance of the raw type (java.util.ArrayList). The target object won't know the difference (because there isn't any difference).

    Basically Java generics is a compile-time trick, with metadata in the compiled classes but just casting at execution time. See the Java generics FAQ for more information.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 14:26

    Generics is largely a compile time feature. What you are trying to do is the same as

    public static void initializeList(Object targetObject, PropertyDescriptor prop, String gtype) {
        prop.getWriteMethod().invoke(targetObject, new ArrayList());
    }
    

    Note: This could change with Types in Java 7.

    0 讨论(0)
提交回复
热议问题