如何引用实例方法

时间:2015-12-27 03:18:37

标签: java reflection

我创建了一个类(Special类),其方法(Special.method())将根据调用Special.method()的方法做出不同的反应。所以,让我们说某些类中的方法X调用Special.method(),如果方法X中存在某些注释,那么当调用方法中不存在这样的注释时,在Special.method()中调用的计算过程将是不同的。此外,由于我将使用第三方库,因此无法保证在调用Special.method()和方法X时将使用相同的线程。

我想知道如何在Java 7中引用实例方法

public class MyClass{
    public void myMethod(){
        ....
    }
}

我知道我可以做到这一点

MyClass.class.getMethod(methodName);

但是这种技术很容易出错,因为它依赖于String输入(即当方法名称改变时等)。是否有更可靠的方法来引用方法?

由于

2 个答案:

答案 0 :(得分:1)

如果没有一些相当粗略的反思,Java不支持方法引用。 Java具有可以像引用一样工作的功能接口,但由于它们的目标用途,它们都至少获取或返回一个值。对于没有参数的方法没有接口,并且在示例中返回9:47:23 PM [Apache] Error: Apache shutdown unexpectedly. 9:47:23 PM [Apache] This may be due to a blocked port, missing dependencies, 9:47:23 PM [Apache] improper privileges, a crash, or a shutdown by another method. 9:47:23 PM [Apache] Press the Logs button to view error logs and check 9:47:23 PM [Apache] the Windows Event Viewer for more clues 9:47:23 PM [Apache] If you need more help, copy and post this 9:47:23 PM [Apache] entire log window on the forums

void

将声明对String#isEmpty()方法的方法引用,该方法返回一个布尔值。 // Assignment context Predicate<String> p = String::isEmpty; 包中存在类似的接口。

https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

关于您的编辑:如果您想找到方法的调用者,请参阅此处:

How do I find the caller of a method using stacktrace or reflection?

答案 1 :(得分:0)

currently-accepted answer不正确:与您的myMethod兼容的功能界面(例如,不接受任何参数,void返回类型),它只是不在java.util.function,它在java.lang中:Runnable

public class MyClass{
    public void myMethod(){
        System.out.println("myMethod was called");
    }
}
class Example
{
    public static void main (String[] args)
    {
        MyClass c = new MyClass();
        Runnable r = c::myMethod;                // <===
        r.run();                                 // <===
    }
}

Live on IDEOne

他们只是没有在java.util.function中复制它。