继承main方法

发布于 2024-09-04 03:48:41 字数 619 浏览 4 评论 0原文

我想定义一个基类,它定义一个实例化该类的主方法,并运行一个方法。但也存在一些问题。这是基类:

public abstract class Strategy
{
    abstract void execute(SoccerRobot robot);

    public static void main(String args)
    {
        Strategy s = new /*Not sure what to put here*/();
        s.execute(new SoccerRobot())
    }
}

这是一个示例派生类:

public class UselessStrategy
{
    void execute(SoccerRobot robot)
    {
        System.out.println("I'm useless")
    }
}

它定义了一个简单的执行方法,应在用作主应用程序时在主方法中调用该方法。但是,为了做到这一点,我需要从基类的 main 方法中实例化派生类。这似乎不可能。

我不想为每个派生类重复 main 方法,因为这感觉有些不必要。

有正确的方法吗?

I want to define a base class that defines a main method that instantiates the class, and runs a method. There are a couple of problems though. Here is the base class:

public abstract class Strategy
{
    abstract void execute(SoccerRobot robot);

    public static void main(String args)
    {
        Strategy s = new /*Not sure what to put here*/();
        s.execute(new SoccerRobot())
    }
}

And here is an example derived class:

public class UselessStrategy
{
    void execute(SoccerRobot robot)
    {
        System.out.println("I'm useless")
    }
}

It defines a simple execute method, which should be called in a main method upon usage as a the main application. However, in order to do so, I need to instantiate the derived class from within the base class's main method. Which doesn't seem to be possible.

I'd rather not have to repeat the main method for every derived class, as it feels somewhat unnessary.

Is there a right way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

猥琐帝 2024-09-11 03:48:41

将 main 方法移出到一个单独的类中。单独关注
策略(名字说明了一切)
启动器(将组件组装在一起并触发执行)

public class Launcher
{
    public static void main(String args)
    {
       Strategy s = new UselessStrategy();
          //OR Strategy s = CreateInstance(args[0]) ;
          //OR equiv mechanism for Dependency Injection if you don't want to hardcode the derived strategy to use.
        s.execute(new SoccerRobot())
    }
}

Move the main method out into a separate class. Separate concerns
Strategy (the name says it all)
Launcher (assembling components together and triggering execution)

public class Launcher
{
    public static void main(String args)
    {
       Strategy s = new UselessStrategy();
          //OR Strategy s = CreateInstance(args[0]) ;
          //OR equiv mechanism for Dependency Injection if you don't want to hardcode the derived strategy to use.
        s.execute(new SoccerRobot())
    }
}
盛夏已如深秋| 2024-09-11 03:48:41

静态方法,例如“main”,不被继承,但可以直接调用。作为解决方法,您可以将类名参数化为 main 方法的参数:

public static void main(String args) throws Exception
{
  String className = (args.length > 0) ? args[0] : 'UselessStrategy';
  Strategy s = (Strategy) Class.forName(className).newInstance();
  s.execute(new SoccerRobot())
}

如果 Class.forName 不可能,则根据 Andreas_D 的评论,维护类名的映射可以提供一个查找表:

private static Map<String, Class<? extends Strategy>> STRATEGY_NAME =
    new HashMap<String, Class<? extends Strategy>>();

static {
    STRATEGY_NAME.put("Useless", UselessStrategy.class);
    STRATEGY_NAME.put("Better", BetterStrategy.class);
}

public static void main(String args[]) throws Exception {
    String className = (args.length > 0) ? args[0] : null;
    Class<? extends Strategy> klass = STRATEGY_NAME.get(className);
    if (klass == null) klass = UselessStrategy.class;
    Strategy s = klass.newInstance();
    s.execute();
}

如果需要的话,可以设计用于维护映射的自动化方法,例如使用反射。

Static methods, such as "main", are not inherited but can be called directly. As a workaround, you could parameterize the class name as an argument to the main method:

public static void main(String args) throws Exception
{
  String className = (args.length > 0) ? args[0] : 'UselessStrategy';
  Strategy s = (Strategy) Class.forName(className).newInstance();
  s.execute(new SoccerRobot())
}

If Class.forName is not possible, then maintaining a mapping of class names can provide a lookup table, per Andreas_D's comment:

private static Map<String, Class<? extends Strategy>> STRATEGY_NAME =
    new HashMap<String, Class<? extends Strategy>>();

static {
    STRATEGY_NAME.put("Useless", UselessStrategy.class);
    STRATEGY_NAME.put("Better", BetterStrategy.class);
}

public static void main(String args[]) throws Exception {
    String className = (args.length > 0) ? args[0] : null;
    Class<? extends Strategy> klass = STRATEGY_NAME.get(className);
    if (klass == null) klass = UselessStrategy.class;
    Strategy s = klass.newInstance();
    s.execute();
}

Automated methods for maintaining the mapping could be devised, such as using reflection, if the need arises.

只有影子陪我不离不弃 2024-09-11 03:48:41

您可以在子类的静态块中定义该类。

public abstract class Strategy
{
    protected static Class<? extends Strategy> instanceClass;

    abstract void execute(SoccerRobot robot);

    public static void main(String args)
    {
        Strategy s = instanceClass.newInstance()
        s.execute(new SoccerRobot())
    }
}

进而

public class UselessStrategy extends Strategy
{
    static {
        instanceClass = UselessStrategy.class;
    }

    void execute(SoccerRobot robot)
    {
        System.out.println("I'm useless")
    }
}

You can define the class in a static block in the subclass.

public abstract class Strategy
{
    protected static Class<? extends Strategy> instanceClass;

    abstract void execute(SoccerRobot robot);

    public static void main(String args)
    {
        Strategy s = instanceClass.newInstance()
        s.execute(new SoccerRobot())
    }
}

and then

public class UselessStrategy extends Strategy
{
    static {
        instanceClass = UselessStrategy.class;
    }

    void execute(SoccerRobot robot)
    {
        System.out.println("I'm useless")
    }
}
昔梦 2024-09-11 03:48:41

您无法实例化抽象类,但绝对可以从基类实例化派生类。所以只需从类定义中删除抽象

public class UselessStrategy

并执行

Strategy s = new UselessStrategy();

You cannot instantiate an abstract class, but you definitely can instantiate a derived class from the base class. So just remove abstract from class definition

public class UselessStrategy

and do

Strategy s = new UselessStrategy();
野の 2024-09-11 03:48:41

我会重新考虑这一点。

将您想要执行的代码放在其他地方,最好是非静态方法,然后调用它。 main() 不应该这样使用。

我建议创建一个单独的策略类来代替 main。

I'd rethink this.

Put the code that you'd like executed somewhere else, preferably a non-static method, and call that. main() shouldn't be used this way.

I'd recommend creating a separate Strategy class in lieu of main.

暖心男生 2024-09-11 03:48:41

main方法是从哪里调用的?如果它需要参数,那么您可以根据这些参数决定具体策略,实例化该策略类并调用它的execute 方法。

Where is the main method called from? If it takes arguments then you can decide a concrete strategy based on those arguments, instantiate that strategy class and call the execute method on it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文