且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过反射调用子类的方法

更新时间:2023-11-30 21:14:40

您正在对空实例调用实例方法 - 因此您收到 NPE 是有道理的.试试这个(将实例传递给 invoke 方法而不是 null):

You are invoking an instance method on a null instance - so it makes sense that you receive a NPE. Try this instead (passing an instance to the invoke method instead of null):

a.getClass().getMethod("Run").invoke(a);

注意:第一次调用有效,因为您可以在空实例上调用静态方法而不会导致 NPE.

Note: the first call worked because you can call a static method on a null instance without causing a NPE.