How to set the generic type of an ArrayList at runtime in java?

前端 未结 4 1112
攒了一身酷
攒了一身酷 2020-12-07 01:32

Ok, so I am setting up my own XML serialization (I know there are others out there, even some built in to Java, but I am doing it myself to learn and because it is so awesom

4条回答
  •  一个人的身影
    2020-12-07 02:05

    No, Generics is only at compile time, only for compile-time type checking, to allow you to avoid casts that can be proven safe at compile-time.

    Think about it. If you could do what you want, it would be completely useless. The whole point of having ArrayList, say, is that when you get an element out of it, the compiler can infer at compile-time that it has type String, and so it allows you to assign it to type String in the code without a cast. Also, if you try to add an element into it, the compiler can check at compile-time that it is of type String, or else not let you do it.

    But you want a type parameter that is not known at compile-time. Thus when you get an element out of it, the compiler doesn't know anything about its type, so you can only assign it to type Object. And when you try to put something into it, the compiler doesn't know what type it's supposed to allow, so it must allow all types? Then there is no point to the generics.

    Thus, you should just use the upper bound type as the type parameter. Like ArrayList list = new ArrayList();

    提交回复
    热议问题