Vote count:
0
I have a bunch of classes that all have the same constructor signature. I have a method that returns an object of that type based on some arguments (which are not the same arguments in the constructor), but I can't seem to figure out how to make a generic method that works for all classes.
Separated as different methods, I may have something like this:
public ImplementationClassA getClassA(long id)
{
SomeGenericThing thing = getGenericThing(id);
return new ImplementationClassA(thing);
}
public ImplementationClassB getClassB(long id)
{
SomeGenericThing thing = getGenericThing(id);
return new ImplementationClassB(thing);
}
As you can see, they're strikingly similar, just the implementation class is different. How do I make a generic method to handle all implementation classes, assuming they have the same constructor?
I took a stab at it, but it's not working because T
isn't recognized... but it feels like something similar to what I want:
public T getImplementationClass(Class<T> implementationClass, long id)
{
SomeGenericThing thing = getGenericThing(id);
return implementationClass.getConstructor(SomeGenericThing.class)
.newInstance(thing);
}
The caller could now simply do getImplementationClass(ImplementationClassA.class, someID)
.
Is this even possible with reflection and generic types?
Aucun commentaire:
Enregistrer un commentaire