繁体   English   中英

从超类static main创建子类

[英]Create subclass from superclass static main

我有一个通用的抽象类( SuperClass )。 我希望有一个main方法,它将是每个子类的默认main方法,并且会做同样的事情,但是使用派生并调用它的适当的子类对象。

像这样:

 public abstract class SuperClass {

    // some code here...

    public static void main(String args[]) {
       // here instantiate the subclass
       // extending this SuperClass, and call
       // some methods
    }
 }

 public SubClass extends SuperClass {
      // here just implement some 
      // abstract methods from SupeClass
      // and NOT implement main()
 }

现在我希望能够将SubClass作为独立程序运行,该程序执行从SuperClass派生的默认main 如何在main方法中实例化正确的SubClass对象?

在C ++,AFAIR中,有一种类似于方法的virtual修饰符,我想在这里会很有用。 在Java中怎么办?

如果希望子类成为应用程序入口点,则不继承静态方法,在子类中编写main方法。

例如,您可以使用Spring IOC

创建一个如下所示的xml文件并放入类路径中:

appconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <bean id="someBean" class="com.company.SubClass"/>

</beans>

然后在您的主代码中,您可以执行以下操作:

   public static void main(String args[]) {
       ApplicationContext context = ClassPathXmlApplicationContext("appconfig.xml");
       SuperClass startClass = (SuperClass) context.getBean("someBean");
       startClass.someMethod();
   }

那么你的SuperClass将不会知道它的子类(但是会知道Spring而不是......)。

您还必须将一些Spring jar文件添加到类路径中。

您不能在子类中继承静态方法,但如果您想在c ++中创建类似虚拟的方法,请将您的方法设为抽象或受保护

如果我希望能够将SubClass作为独立程序运行,那么你的意思是你希望能够运行类似java my.app.SubClass东西,这是行不通的,因为正如大家已经指出的那样,静态方法是没有继承。

根据您想要这个奇怪的子类嵌套的原因,您可以通过实现非静态main来找到解决方法,如下所示:

public class SuperClass{ 
  public static void main(String[] args) {
     SuperClass c = //figure out which class to load via a factor or something
     c.nonStaticMain(args);
  }
  protected void nonStaticMain(String[] args) {
    //do everything from your old main() here
  }
} 

暂无
暂无

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

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