jeudi 16 juillet 2015

Java reflection - invoke an static method [duplicate]

This question already has an answer here:

I tried to use reflection to call a static method, and follow the instruction at How do I invoke a private static method using reflection (Java)? However, I got an NPE error and couldn't figure out why. Does any one have any idea what I did wrong here? Thanks!

            Class<?> builderClass = Class.forName("org.myproject.myclass");
            System.out.println(builderClass.toString());
            java.lang.reflect.Method method = builderClass.getDeclaredMethod("myPrint");
            System.out.println("method = " + method);
            method.setAccessible(true);
            method.invoke(null);


Then I got the following output:

class org.myproject.myclass
method = public void org.myproject.myclass.myPrint()

but got an NullPointerException at the line:

method.invoke(null);


Here is myClass code:

package org.myproject;

public class myclass {

    public void myPrint() {
        System.out.println("my Print");
    }
}

What did I do wrong here? Thanks!





Aucun commentaire:

Enregistrer un commentaire