简体   繁体   English

如何使用反射在java中调用void方法

[英]How to call a void method in java using reflection

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. 如果我使用反射调用方法,我可以让它正常工作而不抛出空指针异常的唯一方法是在我调用的方法中返回一个int值。

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. 将返回类型更改为void并调用它似乎总是抛出空指针异常。 Do I need to change how I am approaching things for void methods? 我是否需要改变我接近无效方法的方法?

Thanks 谢谢

Can you show us where the NullPointerException is thrown? 你能告诉我们抛出NullPointerException位置吗? This codes works correctly: 此代码正常工作:

public void setScore(int n)
{
    this.score = n;
}

Note that I simplified your code a bit using varargs: 请注意,我使用varargs简化了一些代码:

Method setScore = builder.getClass().getMethod("setScore", int.class);
Object returnValue = setScore.invoke(builder, theScore);

Obviously in this case returnValue is null . 显然在这种情况下returnValuenull

If your method no longer returns anything, don't assign the result of invoking it: 如果您的方法不再返回任何内容,请不要分配调用它的结果:

setScore.invoke(builder, new Object[]{theScore});

That alone won't be it , though: The only reason I can see for you getting a NullPointerException would be if you'd tried to use that variable you assigned the result to ( returnValue ) later, since invoke returns null if the method's return type is void . 但这并不是唯一的原因:我可以看到你获得NullPointerException的唯一原因是你曾经尝试过使用你将结果分配给( returnValue )的变量,因为如果方法的返回, invoke返回null类型void

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM