Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/reflection - where's error?

I found some posts about java/reflection on this site. But still can't understand something. Could anyone tell where's error in my code? (need to print "HELLO!")

Output:

java.lang.NoSuchMethodException: Caller.foo()

Here's my Main.java:

import java.lang.reflect.*;

class Main {

    public static void main(String[] args) {
        Caller cal = new Caller();
        Method met;
        try {
            met = cal.getClass().getMethod("foo", new Class[]{});
            met.invoke(cal);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

class Caller {
    void foo() {
        System.out.println("HELLO!");
    }
}
like image 428
Alf Avatar asked Jan 16 '23 05:01

Alf


1 Answers

getMethod() only finds public methods. Either change the access modifier of the Caller#foo() method to public, or use getDeclaredMethod() instead.

like image 85
Keppil Avatar answered Jan 30 '23 16:01

Keppil