首页 > 解决方案 > 如何在构造函数的 super() 方法调用中使用子类变量 (this) 初始化其他类?

问题描述

我正在尝试构建一个类库,可以在未来的 Swift 游戏项目中使用(只需最少的代码调整),这些类将用于创建更具体到我正在处理的当前项目的子类。但是,我在构造函数的 super() 方法调用中使用“this”初始化其他类时遇到了问题。这是代码形式的问题:

public class App extends JFrame {
    public App(AppRunner appRunner, AppPanel appPanel) {
        this.appRunner = appRunner;
        this.appPanel = appPanel;
    }
}


public class Pong extends App {
    public App() {
        super(new AppRunner(10, this), new AppPanel(this));
    }
}

这会在类初始化之前发送与使用“this”变量相关的错误。

我考虑在 App 类中使用抽象方法并让子类实现它们,但我决定不喜欢那样。计划(代码形式):

public abstract class App extends JFrame {

    public App() {
        this.appRunner = initializeAppRunner();
        this.appPanel = initializeAppPanel();
    }

    abstract AppRunner initializeAppRunner();

    abstract AppPanel initializeAppPanel();
}

我还使用一点泛型和反射(我对此知之甚少)测试了一种方法。我也不喜欢这个,因为我不能很容易地更改类的构造函数参数。以下是我当前的代码:

public class App extends JFrame {
    public App(Class<? extends AppRunner> appRunnerClass, Class<? extends AppPanel> appPanelClass) {
        try {
            this.appRunner = appRunnerClass.getConstructor(Integer.class, App.class).newInstance(10, this);
            this.appPanel = appPanelClass.getConstructor(App.class).newInstance(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        add(appPanel);
    }
}

public class Pong extends App {
    public Pong() {
        super(AppRunner.class, PongPanel.class);
    }
}

我想我想知道他们是否有更简单的方法来做到这一点,或者我是否应该使用泛型/抽象方法示例。

标签: javathis

解决方案


仅使用的任何问题:

public Pong() {
    appRunner = new AppRunner(10, this);
    appPanel = new AppPanel(this);
}

——

您可以将 lambda 函数传递给 App 构造函数,允许您自定义实用程序类的创建,但让 App 超类创建这些类。

函数界面

class App extends ... {
    App( Function<App, AppRunner> runner_creator,
         Function<App, AppPanel> panel_creator) {
        appRunner = runner_creator.apply(this);
        appPanel = panel_creator.apply(this);
}

class Pong extends App {
    Pong() {
        super(
            app -> new PongRunner(10, app),
            app -> new PongPanel(app));
    }
}

您将 lambda 函数(没有任何this引用)传递给超类,因此派生类控制实用程序类的创建方式以及使用的特定类。

注意:这些实用程序类是使用超类的this引用构造的,它是一个App,而不是派生类类型。


推荐阅读