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!");
}
}
getMethod()
only finds public
methods. Either change the access modifier of the Caller#foo()
method to public
, or use getDeclaredMethod()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With