2013-12-18 19 views
-1

這裏是我的主要目標:如何從主方法的外部訪問主方法中實例化的對象?

public static void main(String[] args) { 
     try { 
      String option = "-f"; 
      String filename = "src/greenhouse/examples4.txt"; 

      if (!(option.equals("-f")) && !(option.equals("-d"))) { 
      System.out.println("Invalid option"); 
      printUsage(); 
      } 

      GreenhouseControls gc = new GreenhouseControls(); 

      if (option.equals("-f")) { 
      gc.addEvent(gc.new Restart(0,filename)); 
      } 
      gc.run(); 

     }catch (ArrayIndexOutOfBoundsException e) { 
      System.out.println("Invalid number of parameters"); 
      printUsage(); 
     } 
     } 

我創建序列化對象GreenhouseControls並保存其狀態,這樣我可以在以後恢復它的方法。它看起來像這樣:

public void saveState() { 
     try{ 
      // Serialize data object to a file 
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("GreenhouseControls.ser")); 
      out.writeObject(**gc**); // Can't do this from outside main method.. 
      out.close(); 

      // Serialize data object to a byte array 
      ByteArrayOutputStream bos = new ByteArrayOutputStream() ; 
      out = new ObjectOutputStream(bos) ; 
      out.writeObject(**gc**); // Can't do this from outside main method... 
      out.close(); 

      // Get the bytes of the serialized object 
      byte[] buf = bos.toByteArray(); 
      } catch (IOException e) { 
      } 
    } 

我不能從內主序列,因爲我有,發生在另一個類的run()方法中出現的關機方法之前序列化。它看起來像這樣:

public abstract class Controller { 
    private List<Event> eventList = new ArrayList<Event>(); 

    public void addEvent(Event c) { 
     eventList.add(c); 
    } 

    public abstract void shutdown(); 

    public void run() { 
     while(eventList.size() > 0) 

     for(Event e : new ArrayList<Event>(eventList)) 
      if(e.ready()) { 
       System.out.println(e); 
      try { 
       e.action(); 
      } 
      catch(ControllerException ex) { 
       System.err.println("Reason: " + ex + "\n"); 
       saveState(); // There is where I want to invoke it.. 
       shutdown(); 
      } 
      eventList.remove(e); 
     } 
    } 
} 

因此,要重申的是,有沒有辦法來訪問的「GC」 GreenhouseControls的主要對象之外?我知道我可以在run()方法內創建一個新的GreenhouseControls對象,但這將是一個沒有任何我需要保存的數據的新實例...對吧?

+2

你的問題看起來不完整 - 什麼對象需要訪問GreenhouseControls實例?你只顯示「主要方法」代碼片段,它只涉及創建一個GreenhouseControls對象,沒有別的。如果這是你完整的主要方法,那麼看起來你試圖從自身內部獲得對GreenhouseControls的引用,如果是,那麼this或GreenhouseControls.this應該是足夠的。如果情況並非如此,那麼請給我們更多的信息,足以讓我們瞭解您的問題。 –

+0

我在編輯中添加了一些更多的代碼。希望這個清理一下。 – LooMeenin

+0

不,不適合我。它仍然在我看來,所有你需要做的,以獲得gc實例是調用'this'或'GreenhouseControls.this'。再次,**你在哪裏試圖獲得實例**?在**什麼對象**? –

回答

1

將其保存在類變量 (也稱爲類的字段)中。 這是正確的方法。

所以這應該到類級別(所有方法之外)。

private static GreenhouseControls gc = null; 

然後,例如,在你的主要方法你只是做:

gc = new GreenhouseControls(); 

並從那裏你的類的任何方法可以訪問gc。

相關問題