如何发送、接收和存储对外部方法的引用



在一个自定义类中,我试图执行通过参数从外部给定的函数。

对我来说,重要的是不必存储对父类或类似类的任何引用,只需存储要调用的方法/函数。

我尝试将方法作为参数发送,但它不起作用。

class A
    // var to store reference to external method
    private Method myMethodReference;  // (says error: never used)
    // the setter to store the reference to the external method
    public void setMethodReference(Method someMethod)
    {
        myMethodReference = someMethod;
    }
    public boolean someFunctionWithinMyClass()
    {
        // call the external method via my reference
        myMethodReference();  // (says error: The method myMethodReference() is undefined)
    }

此外,当我试图从外部类设置对方法的引用时,它不起作用:

class B
    public void someFunction() { Log.i("la", "la" };
    instanceOfClassA.setMethodReference(someFunction); // (says error: variable someFunction not found)

因此,即使传递引用也不起作用,因为Eclipse假设someFunction是不在作用域中的变量。

我希望这能更好地解释它!

private Method  onClick;

上一行将生成一个错误。。。。

您应该以这种方式创建或声明一个方法。。。

public onClick(){

}

public abstract onClick();

现在。。。。您调用了onClick()而没有实现导致错误的onClick()

最新更新