Depressio
Depressio

Reputation: 1379

Calling constructors via reflection without casting using generics

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?

Upvotes: 1

Views: 80

Answers (1)

rgettman
rgettman

Reputation: 178263

The generics syntax needs T to be declared. In a generic method, place the declaration of the generic type parameter in <> (e.g. <T>) before the return type, which is T:

public <T> T getImplementationClass(Class<T> implementationClass, long id)

If all your implementation classes implement some interface or subclass some base class, then you may want to place a bound on T:

public <T extends BaseClassOrInterface> T getImplementationClass(
    Class<T> implementationClass, long id)

Upvotes: 2

Related Questions