簡體   English   中英

Java:在靜態方法中從超類創建子類的實例

[英]Java: Creating an Instance of a Subclass from the Superclass in a static method

我正在嘗試從我的超級類創建一個子類的新實例。 這是我的超級班

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;
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM