简体   繁体   中英

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

I am trying to create a new Instance of a subclass from my Super Class. This is my 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;
    }

}

And this is my subclass

public class Factory extends Worker {

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

}

And this is what I want to do with those classes.

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

}

Is there any way I can do this without starting over? Thanks for any help.

Is this what you want?

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

Edit:

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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