简体   繁体   English

Java,返回方法作为参考

[英]Java, return method as reference

Im beginner JAVA developer. 我是初学者JAVA开发者。 Here is a method: 这是一个方法:

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

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

it doesnt matter what it does - if it finds something, then returns a Method - if not, the notFound() method itself should be returned. 它无关紧要 - 如果它找到了什么,然后返回一个Method - 如果没有,则应该返回notFound()方法本身。 So the hot spot is at the return notFound; 因此,热点在return notFound; line: if I use return notFound(); line:如果我使用return notFound(); then it returns its value, not the method itself. 然后它返回它的值,而不是方法本身。 I want something like a reference/pointer. 我想要像引用/指针这样的东西。 So getSomething() returns something what can be called, and if the returned method is used wrong, it should trigger that Exception - so its not an option to replace return notFound; 所以getSomething()返回可以调用的东西,如果返回的方法使用错误,它应该触发异常 - 所以它不是替换return notFound;的选项return notFound; with throw new Exception(); with throw new Exception(); ! Or the 2nd option is to create a lambda method.... 或者第二个选项是创建一个lambda方法....

You need to call 你需要打电话

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

to get the notFound method of the current/this object's class. 获取当前/此对象类的notFound方法。

So just do this: 所以这样做:

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

More details here: 更多细节在这里:

Class.getMethod Class.getMethod

EDIT: 编辑:

You can retrieve ie get and call private methods too via reflection. 您可以通过反射检索即获取和调用私有方法。

Here is an example. 这是一个例子。

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);
    }       
}

You need to use reflection to achieve this: 您需要使用反射来实现此目的:

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

eg to get all methods of a given class: 例如,获取给定类的所有方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM