我只是搜索论坛,但没有发现类似的问题。
我的问题是我在使用varargs构造函数时遇到NullPointerException。
我只是在我的一个程序中需要varargs并尝试了我的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)会导致NullPointerException,但我不知道如何处理它。
当我通过JUnit测试它时,我会写一些函数调用: (顺便说一句。我所有的函数调用都失败了)
Book b1 = new Book(“Eragon”,1990,“Eric Cartman”,“Kenny”);
Book b2 = new Book(“Eragon”,1990,“Eric Cartman”);
堆栈跟踪:
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
答案 0 :(得分:1)
没有迹象表明您曾为this.authors
分配了非空值。在某些时候你会想要像:
this.authors = new ArrayList<String>();
或者只是将其初始化为声明的一部分:
private final List authors = new ArrayList();
请注意,完全独立于varargs。您可以将语句硬编码为:
this.authors.add("Foo");
this.authors.add("Bar");
你会得到相同的结果。