[英]How can I use Java Reflection in this application
我想在我的应用程序中使用Reflection API。 我有一个Interface及其实现类,其中包含所有Method声明,如图所示。
请让我知道如何为上述代码使用反射。
我已经开始编写客户端类,但是我不确定这是正确的还是错误的? 请让我知道如何调用该方法
请帮我
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;
}
以及上面接口的实现类,如图所示
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 ??
}
}
我可以看到您的接口扩展了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);
}
}
private Object callMethod(String methodName, CodeHandler object, String strParamForMethod)
{
try
{
Method method = DataHandler.class.getDeclaredMethod(methodName, null);
method.setAccessible(true);
method.invoke(object, strParamForMethod);
}
catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
{
}
}
logon(String message)是您的示例中的实例方法; 您必须先创建CodeHandler实例才能调用它(有关方法,请参阅Saintali的答案)。 如果您声明该方法为静态方法,则可以通过以下方式调用它:
method.invoke(null, message);
有关更多详细信息,请参见Method API 。
在您提到的注释中,您只想在类CodeHandler中调用方法登录。 因此,您不应该使用反射,而是这样做:
public class Client {
public static void main(String args[]) {
callMethod("logon");
}
private Object callMethod(String message) {
CodeHandler codeHandler = new CodeHandler();
codeHandler.logon(message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.