dimanche 16 mai 2021

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());
                }
            }           
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire