Assuming all the built objects have a no-arg constructor (and a bunch of other assumptions), you can use this idiom:
class Builder<SHAPE extends Shape> {
public final SHAPE shape = build();
@SuppressWarnings("unchecked")
private SHAPE build() {
try {
ParameterizedType parent =
(ParameterizedType) getClass().getGenericSuperclass();
Class<?> arg = (Class<?>) parent.getActualTypeArguments()[0];
return (SHAPE) arg.newInstance();
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
public SHAPE shape() { return shape; }
}
But be warned that this may hide a problem with your design.
Why you should anyway look for alternatives
Static methods are convenient when you know how to use them, otherwise they will bite you. Without cheating with reflection, static methods must be invoked by naming the enclosing class in the very source code, making the code effectively impossible to reuse. Also, static methods are not virtual, ie subclasses can't override the parent behavior - again, you can cheat by using reflection and dispatch the call yourself.
Why it doesn't work
The construct
public class Foo<T extends MyOuter> {
public String bar() {
return T.MyNested.aStaticMethod();
}
}
accessing static members on a type variable, is rarely seen (demo). Method signatures are resolved at compile time, so the value of T
has no chance to be read (and, even if it were, type arguments don't survive the compilation step in Java). The type searched is resolved recursively and T
is replaced with its upper bound, leading to the class name XmlObject.Factory
.