简体   繁体   English

如何在Android Studio中使用扩展类的构造函数和方法'getDeclaredConstructor'实例化具有类类型的类

[英]How to Instantiate a class with the class type, using constructor of extended class with method 'getDeclaredConstructor', in Android Studio

public class MainMenu extends GameMenu{

Table table;

Skin skin;

public MainMenu(){super();};

protected void loadWidgets(){

    skin.add("playButton", com.mygdx.game.LIBGDXwrapper.gameGUI.widgets.MainMenuWidgets.loadPlayButton(table));
    table.row();
    skin.add("hightScoreButton", com.mygdx.game.LIBGDXwrapper.gameGUI.widgets.MainMenuWidgets.loadHighScoreButton(table));
    //table.row();
}

protected void loadInputlisteners(){
    skin.get("playButton", Button.class);

}

@Override
public String toString(){
    return "Menu";
}
}





public abstract class GameMenu extends Stage{

private Settings gameSettings;

//public GameMenu(Settings gameSettings){
 //   this.gameSettings = gameSettings;
//}

public GameMenu(){};

protected abstract void loadWidgets();

protected abstract void loadInputlisteners();

}



private static enum GameMenus {MainMenu(MainMenu.class);
    private final Class<? extends GameMenu> menuType;

    GameMenus(Class<? extends GameMenu> menuType){
        this.menuType = menuType;
    }

    public Class<? extends GameMenu> createInstance(Settings gameSettings){
        GameMenu gui = menuType.getDeclaredConstructor().newInstance();
    }
};

I have been trying to make this work for hours now, is it possible to get an instance of a derived class from 'GameMenu' with the class type 'Class< ? 我一直在尝试使它工作数小时,是否有可能从'GameMenu'中获得类类型为'Class <的派生类的实例? extends GameMenu>'? 扩展GameMenu>'? Note that all derived classes of 'GameMenu' have a constructor that with one argument 'Settings'. 请注意,“ GameMenu”的所有派生类都有一个带有一个参数“ Settings”的构造函数。

I'm getting NoSuchMethodExpection from the method 'getDeclaredConstructor'. 我从方法'getDeclaredConstructor'中获取NoSuchMethodExpection。

I would be very grateful if anyone could help me. 如果有人可以帮助我,我将不胜感激。

So you said: 所以你说:

Note that all derived classes of 'GameMenu' have a constructor that with one argument 'Settings'. 请注意,“ GameMenu”的所有派生类都有一个带有一个参数“ Settings”的构造函数。

But you use: 但是您使用:

menuType.getDeclaredConstructor()

If you take a look at the javadoc , you will see that getDeclaredConstructor() returns the "no args" constructor if any. 如果看一下javadoc ,您将看到getDeclaredConstructor()返回“ no args”构造函数(如果有)。 You probably want to specify the constructor argument type: 您可能要指定构造函数参数类型:

menuType.getDeclaredConstructor(Settings.class)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM