0
我只是通過論壇搜索,但還沒有找到類似的問題。Java - 可變參數引起空指針異常
我的問題是,我使用的可變參數構造函數時得到一個NullPointerException異常。
我只需要在我的一個程序中使用可變參數,並嘗試了我的Java書的解決方案,但它不起作用!
我的代碼如下:
/** The author list. */
private List<String> authors;
/**
* Instantiates a new book.
*
* @param title the book title
* @param year the year the book was written
* @param authors the authors
*/
public Book(String title, int year, String... author)
{
{...}
if (author.length < 1)
{
throw new IllegalArgumentException
("A book needs a least 1 author!");
}
for (String e : author)
{
this.authors.add(e);
}
}
我覺得this.authors.add(E)導致空指針異常,但我不知道如何處理它。
由於蔭通過的JUnit測試它,我只會寫一些函數調用: (順便說一句我所有的函數調用失敗。)
書B1 =新的書(「伊拉龍」,1990年,「埃裏克·卡特曼」 「肯尼」);
預訂B2 =新預訂( 「伊拉龍」,1990年, 「埃裏克卡特曼」);
堆棧跟蹤:提前
java.lang.NullPointerException
at de.imbus.training.itbbj.books.Book.<init>(Book.java:57)
at de.imbus.training.itbbj.books.BookTests.creationTestSuccessful(BookTests.java:20)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
謝謝:) TLS
該死的,謝謝..我只是實現了界面,忘記了初始化列表... 多可恥:( – TLS 2012-04-02 14:27:36