我想知道在Java中向外部函数添加回调(最好是作为参数,因为我大部分时间都在使用公共静态方法)的最佳方法是什么,例如将文本追加到文本区域控件中。我不想将引用传递到文本区域。

我对Java相当陌生,因此提出了一个me脚的问题。

最佳答案

根据我的理解,您希望能够调用一种更新文本区域的方法,而无需直接调用它。
即您简单地想要发送方法的名称。

在代码中显示输出(您可以在此处添加代码,以将其显示在特定的文本区域中)

但是我们不想直接调用方法,我们让程序根据提供的回调信息来调用方法。

我们使用反射的概念来初始化类,调用方法等

类:MainCallBack.java


我们传递要调用的方法的名称,
函数displayAnswer(int,String)将使用要显示的数字以及必须调用的方法。 (不确定这是否是CallBack的意思)


我在每一行中添加了注释,以解释该功能的作用。

displayAnswer中的以下代码行进行了实际的调用。

methods[i].invoke(classObject, answer);


如果要调用静态方法,请使用“ null”代替“ classObject”

methods[i].invoke(null, answer);


在包com.callback中创建的类
为了减少代码行数,我使用Exception而不是特定的异常。

类MainCallBack.java

package com.callback;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainCallBack {

    public static void main(String[] args)
    {

        MainCallBack mainCallBk = new MainCallBack();

        String sCallBackMethodName = "displaySumInTextArea"; //this is the name of the callback method.

        int z = 11 ;
        mainCallBk.displayAnswer( z , sCallBackMethodName );
    }
    private void displayAnswer(Integer answer , String sCallBackMethod)
    {
        try {
            Class className = Class.forName("com.callback.CallBackClass"); //will assume that we know the class name
            Constructor classConstructor = className.getConstructor(); // get the constructor of the class.
            Object classObject = classConstructor.newInstance(); //create an instance.

            Method[] methods = className.getDeclaredMethods();   //get all methods within the class.

            for (int i = 0; i < methods.length; i++)
            {
                String dataMethod = methods[i].getName();   // iterate through array of methods and get each name
                if(dataMethod.equalsIgnoreCase(sCallBackMethod))  //comparing callbackname with every method in class.
                {
                    methods[i].invoke(classObject, answer);     // invoke the method if they match with what the user is calling.
                                    // if 'displaySumInTextArea( int )' was static then we would use 'null' (without quotes) in place of the classObject.
                }
            }

        } catch (Exception e) {
            e.printStackTrace(); //use specific exceptions here
        }
    }
}


CallBackClass.java类

package com.callback;

public class CallBackClass {

    public void displaySumInTextArea(Integer sum)
    {
        System.out.println("Sum = " + sum);
    }
}


我希望这回答了你的问题

10-07 18:54
查看更多