I'm trying to build a factory of object instances of a type T extends BaseClient, with the returned instances having one of the methods of T overloaded to perform some additional logic. I cannot modify the code of the T classes (which is why I need the overloading), nor that of the base abstract class BaseClient.
This is easy to do with concrete, well-defined types. For example, given a FooClient extends BaseClient, I can do this:
public class FooClientFactory {
public static FooClient create() {
return new FooClient() {
@Override
public void theMethod() {
super.theMethod();
someAdditionalLogic();
}
};
}
}
But in a world where I need to deal with potentially many different types of clients (all subclasses of BaseClient), I would ideally like to have something like this:
public class ClientFactory<T extends BaseClient> {
public static T create() {
return ...;
}
}
So I don't have to duplicate the above code for each concrete subclass.
Unfortunately, it's not possible to write new T() { ... }. It's also not possible to use a Class<T> and call newInstance() on it, since that doesn't allow me to override the behavior of theMethod(). Using a Proxy instance would allow me to intercept method calls and match on the method name (ugly) to perform someAdditionalLogic() when required, but because BaseClient is not an interface -- and I can't make it be one -- I can't build a proxy (to be more precise in my actual use case, I do have an interface I can use, specific to each client, but there are places where the returned instance needs to be cast to a BaseClient, which the returned Proxy instance does not "technically" implement/advertise because of how proxy instances work, leading to ClassCastExceptions).
So, what gives? Is this at all possible in Java, or is copy-pasting FooClientFactory for each XXClient type my only option?