Java:在静态方法中从父类(super class)创建子类的实例

标签 java inheritance static-methods

我正在尝试从我的 super 类创建子类的新实例。这是我的 super 类(class)

public abstract class Worker {

    String world;

    protected abstract void onLoad(Scanner read);

    public static Worker load(Scanner read) {
        // I want to create the instance of my sub class here and call it w
        w.onLoad(read);
        return w;
    } 

    public void setWorld(String world) {
        this.world = world;
    }

}

这是我的子类

public class Factory extends Worker {

    @Override
    protected onLoad(Scanner read) {
        setWorld(read.readline());
    }

}

这就是我想要对这些类执行的操作。

public class MainClass{

    public List<Factory> loadFactories() {
        List<Factory> facts = new ArrayList<Factory>();
        Scanner read = new Scanner(new FileInputStream("factory.txt"));

        while(read.hasNextLine()) {
            Factory f = (Factory)Factory.load(read);
            facts.add(f);
        }

        read.close();
        return facts;
    }

}

有什么方法可以让我不用重新开始就可以做到这一点?感谢您的帮助。

最佳答案

这是你想要的吗?

public static Worker load(Scanner read) {
    Factory w=new Factory();
    w.onLoad(read);
    return w;
} 

编辑:

public class MainClass {

    public List<Factory> loadFactories() throws FileNotFoundException, InstantiationException, IllegalAccessException {
        final List<Factory> facts = new ArrayList<Factory>();
        final Scanner read = new Scanner(new FileInputStream("factory.txt"));

        while (read.hasNextLine()) {
            final Factory f = Worker.load(read, Factory.class);
            facts.add(f);
            final Pipeline p = Worker.load(read, Pipeline.class);
        }

        read.close();
        return facts;
    }

    static public class Factory extends Worker {

        @Override
        protected void onLoad(final Scanner read) {

        }

    }

    static public class Pipeline extends Worker {

        @Override
        protected void onLoad(final Scanner read) {

        }

    }

    static public abstract class Worker {

        String world;

        protected abstract void onLoad(Scanner read);

        public static <T extends Worker> T load(final Scanner read, final Class<T> t) throws InstantiationException, IllegalAccessException {
            final T w = t.newInstance();
            w.onLoad(read);
            return w;
        }

        public void setWorld(final String world) {
            this.world = world;
        }

    }
}

关于Java:在静态方法中从父类(super class)创建子类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335569/

相关文章:

java - int 和 double 除以 double java

c# - 这个 C# 构造在做什么,为什么? MyClass<TMyClass> : MyClass where

c++ - 不明确的类继承

mysql_close() : supplied argument is not a valid MySQL-Link resource

c++ - 在构造函数中调用静态方法

java - 使用 IE8 时的 GWT 问题

java - KafkaConsumer.commitSync() 实际提交了什么?

java - 如何设置带有空字符串的 Vaadin 标签的宽度

c++ - 调用unique_ptr子类继承的模板构造函数

Python:私有(private)内部枚举类中的静态方法