2013-10-07 113 views
0

我正在修改一個程序,它有Class[] paramTypes來存儲輸入類型。那麼我的問題是我如何爲數組的每個單元賦值? 我可以這樣做paramTypes = new Class[]{int.class,double.class,String.class}爲paramTypes分配,但是當我嘗試爲paramTypes[i] = int.class這樣的for循環分配每個單元時,它顯示NullPointerException。那麼我該怎麼做這個for循環呢?如何爲類數組對象賦值?

這是方法:

public MethodCall(String className, 
     String methodName, 
     Class[] paramTypes, 
     Object[] params) { 
    this.className = className; 
    this.methodName = methodName; 
    this.paramTypes = paramTypes; 
    this.params = params; 
} 

這是實例:

MethodCall methodCall = new MethodCall("Foo", "bar", new Class[]{int.class,double.class},new Object[]{new Integer(10), new Double(123.0)}); 

回答

0

你必須首先初始化數組。

paramTypes = new Class[4]; // or some other number 
for(...){ 
    paramTypes[i] = int.class; 
} 
+0

我可以動態初始化數組嗎?因爲我不知道輸入長度。 – CodTango

+0

你的意思是你有一個變量的大小?是的你可以。你爲什麼不試一試! – Mohayemin