forhas
forhas

Reputation: 12001

Java Generics run-time instantiation

I have my generic interface:

public interface myGenericInterface<T> {...}

And I have a class retrieved this way:

Class<?> myClass = Class.forName("myClassName");

I would like to be able to instantiate something like this:

myGenericInterface<myClass> mySubType ...

It's not working of course. Is there a way of doing something like that?

UPDATE:

Well, since generics is relevant to compile-time I guess it won't work with reflection style code. So no good can come out of that.

Upvotes: 0

Views: 143

Answers (2)

kodstark
kodstark

Reputation: 490

When you declare object with generics in class field then Field reflection object from this class keeps what kind of generic was declared.

static class ClassA {
    public List<String> field = new ArrayList<String>();
}

public static void main(String[] args) throws Exception {
    Field field = ClassA.class.getField("field");
    Class<?> genericType = getGenericType(field);
    System.out.println(genericType);
}

private static Class<?> getGenericType(Field field) {
    final Type type0 = field.getGenericType();
    if (type0 instanceof ParameterizedType) {
        final Type type = ((ParameterizedType) type0).getActualTypeArguments()[0];
        if (type instanceof Class<?>) {
            return (Class<?>) type;
        }
        // miss code for method arguments
    }
    return Object.class;
}

Code prints class java.lang.String and can be useful in your case but basically raw Class object doesn't carry generics information - as generics information are used only on compile time and not runtime time.

Upvotes: 1

Pino
Pino

Reputation: 9383

Generics are a compile-time feature that helps to avoid programming errors, so what you are trying to do makes no sense, sorry.

Upvotes: 2

Related Questions