简体   繁体   中英

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:

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. 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. 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();
        }
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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