How do I build Java typed objects at runtime from generic type definitions and runtime type parameters?

Assume universal type declaration (Java)

class Foo<T> {
    public T bar;
}

At runtime, how do I instantiate a type object that represents foo parameterized by a specific type T (also known only at runtime)?

Solution

I think I understand your problem You want to serialize a foo & T class object that you have t at runtime (but it is not fixed at compile time) Therefore, the proposed solution of gson to create an anonymous subclass of typetoken does not work, because it requires parameterized types (such as foo < string >) to be hard coded at compile time. If you use an anonymous subclass like foo <; T> ;. However, let's see how the typetoken method on the gson site is actually implemented You create an object of an anonymous subclass of typetoken, and then use its GetType () method to request its type parameters The superclass of a class is part of its metadata and includes the general parameters of its superclass Therefore, at run time, it can view its inheritance hierarchy, find out the type parameters you use for typetoken, and then return the Java. XML of that type lang.reflect. Type instance (parameterizedtype instance if parameterized) Once you get this type instance, you should pass it to togson () as the second parameter All we need to do is find another way to create parameterizedtype instances Parametrizedtype is an interface, but unfortunately, the public Java API does not provide any specific implementation or create parametrizedtype dynamically in any way There seems to be a class called parameterizedtypeimpl that can be used in the private sun API and gson code (e.g. here) You can simply copy the code and rename it to your own class Then, create a new parameterized typeimpl (foo. Class, new type [] {string. Class}, null) (untested) that indicates foo < string > at runtime

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>