gpt4 book ai didi

java - 如何在此应用程序中使用 Java Reflection

转载 作者:行者123 更新时间:2023-12-01 19:00:25 24 4
gpt4 key购买 nike

我想在我的应用程序中使用 Reflection API。我有一个接口(interface)及其实现类,所有方法声明如图所示。

请让我知道如何对上述代码使用反射。

我已经开始编写客户端类,但我不确定这是否正确?请让我知道如何调用该方法

请帮助我

public interface DataHandler extends Remote {

public abstract String logon(String message) throws RemoteException;
public abstract String logoff(String message) throws RemoteException;
public abstract String userinformation(String message) throws RemoteException;
public abstract String updateUser(String message) throws RemoteException;
}

以及如图所示的上述接口(interface)的实现类

public class CodeHandler implements DataHandler
{
public String logon(String message) throws RemoteException {}
public String logoff(String message) throws RemoteException {}
public String userinformation(String message) throws RemoteException {}
public String updateUser(String message) throws RemoteException {}
}

我有一个如图所示的客户端类

public class Client
{
public static void main(String args[])
{
callMethod("logon");
}

private Object callMethod(String message) {
String methodName = message ;
Method method = DataHandler.class.getDeclaredMethod(methodName, null);
method.setAccessible(true);
// How to use method.invoke in this case ??
}
}

最佳答案

我可以看到你的接口(interface)扩展了java.rmi.Remote,所以我猜你必须在这里使用RMI工具而不是反射,但如果你真的需要要使用反射,请尝试这样的操作:

private Object callMethod(CodeHandler codeHandler, String methodName, String message) {
try {
Method method = DataHandler.class.getDeclaredMethod(methodName, String.class);
method.setAccessible(true);

return method.invoke(codeHandler, message);
} catch (NoSuchMethodException e) {
handle(e);
} catch (IllegalAccessException e) {
handle(e);
} catch (InvocationTargetException e) {
handle(e);
}
}

关于java - 如何在此应用程序中使用 Java Reflection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12462288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com