Java,返回方法作为参考

时间:2014-07-28 10:29:15

标签: java

我是初学JAVA开发人员。这是一种方法:

private Method getSomething()
{
    for (Method m : getClass().getDeclaredMethods())
    {
        return m;
    }
    return notFound;
}

private void notFound()
{
    throw new Exception();
}

它无关紧要 - 如果它找到了什么,然后返回Method - 如果没有,则应返回notFound()方法本身。所以热点位于return notFound;行:如果我使用return notFound();则返回其值,而不是方法本身。我想要像引用/指针这样的东西。所以getSomething()返回可以调用的内容,如果返回的方法使用错误,它应该触发异常 - 因此它不能用return notFound;替换throw new Exception();! 或者第二个选项是创建一个lambda方法....

2 个答案:

答案 0 :(得分:8)

您需要致电

this.getClass().getMethod("notFound")

获取当前/此对象类的notFound方法。

所以就这样做:

return this.getClass().getMethod("notFound");

此处有更多详情:

Class.getMethod

修改

您可以通过反射检索即获取和调用私有方法。

这是一个例子。

import java.lang.reflect.Method;


public class Test001 {

    public static void main(String[] args) throws Exception {
        Test002 obj = new Test002();
        Method m = obj.getClass().getDeclaredMethod("testMethod", int.class);
        m.setAccessible(true);

        m.invoke(obj, 10);
        m.invoke(obj, 20);

        System.out.println(m.getName());
    }


}

class Test002 {
    private void testMethod(int x){
        System.out.println("Hello there: " + x);
    }       
}

答案 1 :(得分:2)

您需要使用反射来实现此目的:

http://docs.oracle.com/javase/tutorial/reflect/

e.g。获取给定类的所有方法:

Class aClass = ...//obtain class object
Method[] methods = aClass.getMethods();