简体   繁体   中英

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. 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...-

Per @markspace, I edited the invoke to add the invoking object:

        m.invoke(myConveyor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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