2013-11-09 36 views
0

我一直在嘗試使用java.lang的newInstace()方法將我的一個類(使用反射加載)存儲到對象中。它似乎在創建newInstace()的方法內工作,但是在它之外,var拋出一個空指針異常......真的對我沒有意義,有沒有人知道如何解決這個問題?Java:將newInstance存儲在變量中

類:

public class ScriptManager { 

public static Class currentScript; 
public static Object ScriptInstance; 
public static int State; 
// 0 = Not Running 
// 1 = Running 
// 2 = Paused 

public static void runScript() { 
    try { 
     ScriptInstance = currentScript.newInstance(); 
     currentScript.getMethod("run").invoke(ScriptInstance); 
     State = 1; 
     MainFrame.onPause(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static void pauseScript() { 
    try { 
     currentScript.getMethod("pause").invoke(ScriptInstance); 
     State = 2; 
     MainFrame.onPause(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static void stopScript() { 
    try { 
     currentScript.getMethod("stop").invoke(ScriptInstance); 
     State = 0; 
     MainFrame.onStop(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

}

錯誤:

java.lang.NullPointerException 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
at Bot.ScriptManager.pauseScript(ScriptManager.java:29) 

回答

0

您使用的static是搞亂你。試試這樣:

public class ScriptManager { 

     private Class currentScript; 
     private Object scriptInstance; 
     private int state; 

     public ScriptManager() { 
     try { 
      scriptInstance = currentScript.newInstance(); 
      currentScript.getMethod("run").invoke(scriptInstance); 
      //the rest 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     } 

     public void pauseScript() { 
     try { 
      currentScript.getMethod("pause").invoke(scriptInstance); 
      //the rest 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     } 
//the rest 
} 

在旁註中,使用較低的CamelCase作爲變量名稱。

並保留您的成員變量private在這種情況下。

+0

我刪除了靜態,它仍然沒有工作:(和什麼是CamelCase? –

+0

那麼,正如我的示例所示,僅僅刪除'static'是不夠的,你需要創建一個構造函數等等。 – Vidya

+0

以下是CamelCase的相關信息:http://en.wikipedia.org/wiki/CamelCase#Programming_and_coding。最後一行是將您的變量重命名爲以小寫字母開頭。 – Vidya