2

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, i.e, 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>();
}
1
  • Generics were invented to help the compiler ensure proper type checking, at compile time (as opposed to making everything an Object and then doing run-time class checks). A generic with a class that isn't known until run time therefore isn't very useful as a generic. I can't propose an alternative solution unless I know what you're really trying to accomplish. For example, what does the inside of your Pojo really look like? What were you hoping would happen when you instantiated your Pojo? Commented May 6, 2016 at 6:45

1 Answer 1

2

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. E.g.:

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();
        }
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.