Assaf Moldavsky
Assaf Moldavsky

Reputation: 1721

Java String to generics type

I have a class defined like this

class MyTransformer<V, M extends SomeBaseM> extends Transformer<V,M> {
  ...
}

In all cases but one I would instantiate it like this

MyTransformer<Foo,Bar> t = new MyTransformer(...);

There is this one case where I get the generic types as a Class instead:

void annoyingCaller( Class<? extends V> vClass, Class<? extends SomeBaseM> M, ... ) {
  MyTransformer<?,?> t = new MyTransformer(...);
}

Is there anything I can do to populate these generic type (via reflection perhaps?)

Upvotes: 0

Views: 68

Answers (2)

LppEdd
LppEdd

Reputation: 21172

You were almost there I suppose.
I don't think this will be useful however, as you'll need to pass in specific Classes, and if you can do that, you already know the generic types.

<V, M extends SomeBaseM> MyTransformer<V, M> annoyingCaller(
        Class<? extends V> v,
        Class<? extends M> m) {
    return new MyTransformer<V, M>();
}

If, instead, you don't need to return the instance, but you just need it as an internal process, it's fine.

void <V, M extends SomeBaseM> annoyingCaller(
        Class<? extends V> v,
        Class<? extends M> m) {
    final MyTransformer<V, M> transformer = new MyTransformer<>();
    transformer.method();
    ...
}

Upvotes: 0

markspace
markspace

Reputation: 11030

Does this work for you?

void annoyingCaller( Class<? extends V> vClass, Class<? extends SomeBaseM> M, ... ) {
  MyTransformer<Class<? super V>, Class<? super SomeBaseM>> t 
         = new MyTransformer<>(...);
}

Upvotes: 1

Related Questions