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

时间:2022-10-25 18:14:38

In a custom Class I'm trying to execute functions that are given externally via parameters.

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

It is important for me not to have to store any reference to parent classes or such, only the methods/functions to be called.

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

I tried sending a Method as a parameter but it isn't working.

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

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

Also, when I try to set the reference to the method from the external class, it doesn't work:

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

class B

    public void someFunction() { Log.i("la", "la" };

    instanceOfClassA.setMethodReference(someFunction); // (says error: variable someFunction not found)

So even passing the reference doesn't work because Eclipse assumes someFunction is a variable that is not in the scope.

因此,即使传递引用也不起作用,因为Eclipse假定someFunction是一个不在范围内的变量。

I hope this explains it better!

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

1 个解决方案

#1


0  

private Method  onClick;

This above line will generate an error....

以上行将产生错误....

You should create or declare a method this way...

您应该以这种方式创建或声明方法......

public onClick(){


}

or

public abstract onClick();

公共抽象onClick();

Now.... you have called onClick() without implementing onClick(), that led to the error.

现在....你调用了onClick()而没有实现onClick(),这导致了错误。

#1


0  

private Method  onClick;

This above line will generate an error....

以上行将产生错误....

You should create or declare a method this way...

您应该以这种方式创建或声明方法......

public onClick(){


}

or

public abstract onClick();

公共抽象onClick();

Now.... you have called onClick() without implementing onClick(), that led to the error.

现在....你调用了onClick()而没有实现onClick(),这导致了错误。