0

I wrote this code

List<Object> result = null;

....
Object resultObject =method.invoke(o, "test", "test");
System.out.println(resultObject);
result.add(resultObject);

resultObject contain the result that I expect but the last line caus a NullpointerException.

4 Answers4

3
List<Object> result = null;

The variable result now contains null.

result.add(resultObject);

You try to call add() on result, but as result is null, a NullPointerException is thrown instead.

You should create the list. Replace the first line with:

List<Object> result = new ArrayList<Object>();
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
0

change your code to

List<Object> result = new ArrayList<Object>();

otherwise result is NULL.

CS Pei
  • 10,869
  • 1
  • 27
  • 46
0

Some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter.

List<YourObject> result = new ArrayList<YourObject>();

Reference Link : Click here

Sireesh Yarlagadda
  • 12,978
  • 3
  • 74
  • 76
0

You are initializing the list to null.In the problem line,you call a method on the list object which is currently null.This is bound to throw a NPE as u cant invoke methods on an object which isn't there.exceptions are static (s) or class members,where in any case the object is ignored and is considered a bad practice to do.eg this would work on a null object- Object=null; Object.clearData();
where clearData() is a class member and shouldn't be called with an object reference. So if new to Java learn this rule -you cannot call methods,or examine variables on an object that is initialized to NULL.Null in java is just an empty reference and not an object.So it won't have any behavior. Initialize it with a concrete type like ArrayList<t>()and it would work.