简体   繁体   English

无法调用通过反射获得的方法

[英]Can't invoke a method obtained through reflection

I am getting the error我收到错误

Cannot invoke "Object.getClass()" because "obj" is null

on the line在线上

            m.invoke(null);

Here are the classes:以下是课程:

package device;

public class Conveyor {
    private String ID;
    
    public Conveyor(String ID) {this.ID = ID;}
    
    public void Start() {
        
    }

    public void Stop() {
        
    }

}


package main;

import java.lang.reflect.Method;

import device.Conveyor;

public class Main {
    
    public static void main(String args[]) {
        
        Conveyor myConveyor = new Conveyor("C1");

        Class<Conveyor> conveyorClass = (Class<Conveyor>) myConveyor.getClass();

        for (Method m : conveyorClass.getMethods()) {
            System.out.println(m.getName());
            if (m.getName().equals("Start")) {
                try {
                    m.invoke(null);
                } catch (Exception ex) {
                    System.err.println(ex.getLocalizedMessage());
                }
            }           
        }
    }
}

Acording to the docs, the invoke method receive the reference of the object that will call the method.根据文档,invoke 方法接收将调用该方法的 object 的引用。 So you need to change the code to be:因此,您需要将代码更改为:

m.invoke(myConveyor);

See the docs https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-请参阅文档https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Z497031794451AC3B5243

Per @markspace, I edited the invoke to add the invoking object:根据@markspace,我编辑了调用以添加调用 object:

        m.invoke(myConveyor);

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

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