2012-11-11 124 views
2

我想从我的超类创建一个子类的新实例。这是我的超级类Java:在静态方法中从超类创建一个子类的实例

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

} 

有什么办法可以做到这一点,而不必重新开始?谢谢你的帮助。

+0

您还没有作出'Worker'一个子类呢。 –

+2

如果你想让Factory成为Worker的一个子类,一个好的开始是编写:'class Factory extends Worker'。 – assylias

+0

什么在factory.txt? –

回答

2

这是你想要的吗?

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

    } 
} 
+1

不知道为什么这是被拒绝投票 - 这是唯一的答案,如果你面对的价值问题! –

+0

对我来说,它看起来像一个工厂设计模式的完美例子!我不可能用另一种方式解释它。当然主要的方法应该是Worker f = Worker.load(read); – thedayofcondor

+0

是的,但不完全一样。假设我有另一个名为Pipeline的Worker类,并且我想告诉它是Pipeline还是Factory(没有枚举)。 – ChrisixStudios

相关问题