I ran into a situation where I need to create a object where the class is parametrized with generic type T. I have access to the class type through a variable of type Class. Is it possible to do something along the lines?
Class clazz = Integer.class;
Foo<clazz> foo = new Foo(); //doesn't work
class Foo<T> {
...
}
My apologizes for not listing the original problem. Original Problem: My goal was to decouple a third party library from my module's API. I added code below explaining my approach.
// third party lib
abstract class ThirdParty<S> {
public abstract S doAction(S s);
}
// exposed to other modules, rather than exposing the third party lib
abstract class ExposedAbstractClass<S> {
public abstract S doAction(S source);
// get hold of type using guava lib
private final TypeToken<S> typeToken = new TypeToken<S>(getClass()) { };
public Class<S> getSourceClass() { return (Class<S>) typeToken.getClass()
}
class Builder<S> extends ThirdPartyLib<S> {
ExposedAbstractClass exposed;
public Builder(ExposedAbstractClass exposed) {
this.exposed = exposed;
}
@Override
public S doAction(S s) {
return (S) exposed.doAction(s);
}
}
//invoke builder
class InvokeThirdParty {
public void invoke (ExposedAbstractClass exposed) {
Class type = exposed.getSourceClass();
Builder<type> builder = new Builder(exposed); //doesn't work since Class is runtime type, and T is compile time type
}
}
Please share if there are better patterns to approach this problem of decoupling a thirdParty lib. My initial design was to add a adapter to third party lib , however the adapter would still have a import from third party lib which i am trying to avoid.
Aucun commentaire:
Enregistrer un commentaire