If I call a method using reflection, the only way I can get it to work properly without throwing a null pointer exception is by returning an int value in the method I’m calling.
For example, the method I want to call:
public int setScore(int n)
{
this.score = n;
return 1;
}
The way I call it:
Method setScore = myClass.getMethod("setScore", new Class<?>[]{int.class});
Object returnValue = setScore.invoke(builder, new Object[]{theScore});
Changing the return type to void and calling it seems to always throw a null pointer exception. Do I need to change how I am approaching things for void methods?
Thanks
Can you show us where the
NullPointerExceptionis thrown? This codes works correctly:Note that I simplified your code a bit using varargs:
Obviously in this case
returnValueisnull.