I asked this question over 10 years ago, about C#, and got a good answer there. Now I'm trying to do the same thing in Java.
Say I have an abstract class Animal
. I want a static method create()
in that class, that will return a value of the type of whatever the subclass is. I managed this in C# using the following structure:
public class Animal<T> where T : Animal<T>, new()
{
public static T Create()
{
var t = new T();
// do generic stuff on the new T instance
return t;
}
}
public class Dog : Animal<Dog>
{
}
//usage:
var dog = Dog.Create();
This worked a charm in C#. But now I'm trying to replicate this structure in Java, and hitting a wall. One big wall is that it seems that you can't have static generic members. So this would seem to be a bit of a showstopper. But I'm an optimistic kind of guy, and maybe some Java expert out there has come up with a totally out of the box pattern for achieving more or less what I'm trying to do here?