4

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!");
    }
}
0

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, the scope for foo() is package-private (no explicit modifier)
Yeah! getDeclaredMethod() - cause I need to keep both classes in the same file.
0
import java.lang.reflect.*;

public static void main(String[] args) {
    public static void main(String[] args) {
        try {
            Class c = Class.forName("Caller"); 
            Object obj = c.newInstance();
            Method m = c.getMethod("foo");
            m.invoke(obj);
        } catch (Exception e) {
            System.out.println(e.toString());
        }           
    }
}

public class Caller {
    public void foo() {
        System.out.println("HELLO!");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.