将构造函数调用传递给其他 class

Pass constructor call on to other class

我有一个生成 UI 的通用 class 和一个应该生成此 class 的更专业版本的子 class。 问题是,superclass 也从多个位置一般调用,所以基本上我必须在 superclass 天气中决定 superclass 应该处理调用还是 "pass it on" 到 child class.

public class AddEntryWindow<T extends SomeUiClass>
{

    public AddEntryWindow(TableDefinition tableDefinition, RefreshListener refreshListener)
    {
        // regular init stuff

        if(T == PartUiClass) // I know this doesn't work like this
        {
            return new AddPartWindow(tableDefinition, refreshListener);
            // I know this doesn't work either.
        }
    }
}


public class AddPartWindow extends AddEntryWindow<PartUiClass>
{

    public AddPartWindow(TableDefinition tableDefinition, RefreshListener refreshListener)
    {
        // (usually super would have to be called here)

        //special init stuff
    }
}

调用如下所示:

new OpenBlockingWindowHandler(scene, new AddEntryWindow<T>(TableDefinitionGenerator.getTableDefinitionByClass(elementToSelect), this)));

这样的结构在 java 中是否可行? 是否有可能让构造函数 "return" 另一个 classes 实例?

Is such a construction somehow possible in java? Is it somehow possible to let a constructor "return" another classes instance?

不,构造函数永远不能 return 另一个 class 的实例。实际上向构造函数添加 any return 语句被认为是 Java.

中的语法错误

The thing is, that the superclass is also called generically from multiple locations, so basically I would have to decide in the superclass weather the superclass should handle the call or "pass it on" to the child class.

您可以向 class 添加一个静态工厂方法,它接受类型参数的运行时 class 作为参数。像这样:

public static <T extends SomeUiClass> AddEntryWindow<T> createAddEntryWindow(TableDefinition tableDefinition, RefreshListener refreshListener, Class<T> c){
    if(PartUiClass.class.isAssignableFrom(c)){
        return (AddEntryWindow<T>) new AddPartWindow(tableDefinition, refreshListener);
    }
    return new AddEntryWindow<>(tableDefinition, refreshListener);
}