4

我在这个网站上找到了一些关于 java/reflection 的帖子。但是还是有些看不懂。谁能告诉我代码中的错误在哪里?(需要打印“HELLO!”)

输出:

java.lang.NoSuchMethodException: Caller.foo()

这是我的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!");
    }
}
4

2 回答 2

10

getMethod()只找到public方法。Caller#foo()要么将方法的访问修饰符更改为public,要么getDeclaredMethod()改用。

于 2012-10-25T12:07:06.140 回答
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!");
    }
}
于 2012-10-25T12:17:09.773 回答