简体   繁体   English

Java使用在运行时获取的类型参数创建通用实例

[英]Java create generic instance with type parameter obtained at runtime

I have a class like this: 我有一个这样的课:

public class Pojo<T, P> {}

I know at compile time the type of T but I don't know the type of P. I was wondering if something like this is possible: 我在编译时知道T的类型,但我不知道P.的类型。我想知道这样的事情是否可行:

Class<Integer> t = Integer.class;
field = new Pojo<Integer, t>();

If not, any alternative solution to the problem is valid ;) 如果没有,问题的任何替代解决方案都是有效的;)

EDIT: I'm trying to obtain statistics from POJO fields, ie, I have a class AirRegister with fields station, o3, so2, altitude, latitude... and I want to obtain the mode for these fields. 编辑:我正在尝试从POJO字段获取统计数据,即我有一个类AirRegister与字段station,o3,so2,altitude,latitude ...我想获得这些字段的模式。 The user can send any type with any field type to the program so until runtime the field type is unknown. 用户可以向程序发送任何具有任何字段类型的类型,因此直到运行时字段类型未知。

Example: 例:

public static void main(String[] args) {
    String field = args[0];
    Class<fieldType> type = AirRegister.class.getDeclaredField(field).getClass();
    ModeImpl<AirRegister, type> p = new ModeImpl<AirRegister, type>();
}

It is not possible. 这不可能。 Generics are a compile-time only feature. 泛型是仅编译时功能。 They are used by the compiler to type-check your source code, but at run-time they are gone. 编译器使用它们来对源代码进行类型检查,但在运行时它们已经消失了。

If you need to implement run-time type checking, you might use Class instances to store the required type. 如果需要实现运行时类型检查,可以使用Class实例来存储所需的类型。 Eg: 例如:

class Pojo<T> {
    private Class<?> clazz;
    Pojo(Class<?> clazz) {
        this.clazz = clazz;
    }
    void doSomething(T arg1, Object arg2) {
        if (!clazz.isInstance(arg2)) {
            throw new ClassCastException();
        }
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM