1

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

They do indeed extend an abstract class. I knew I was missing something with the generics! Usually when I use them, they're defined at the class level (e.g. implements SomeInterface<ImplClass1,ImplClass2>), but I've not done a method like this before. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.