java - 使用 execute 方法创建了一个 Task 接口。如何让它动态接受参数 - JAVA
问题描述
界面
public interface ITask<T> {
T execute() throws RemoteException, SQLException;
}
其实施
public interface IRMI extends Remote {
<T> T executeTask(ITask<T> t) throws SQLException, RemoteException;
}
public <T> T executeTask(ITask<T> t) throws SQLException, RemoteException {
return t.execute();
}
所以我想要类似的东西
public void registerUserTask() throws SQLException, RemoteException {
new CreateUser().execute(username, password, email);
}
解决方案
您必须将execute
方法参数从现在的无参数更改为参数数组。
例如,如果您知道需要传递的所有参数都是String
s,您可以将执行方法更改为:
public interface ITask<T> {
T execute(String ... params) throws RemoteException, SQLException;
}
在此接口的实现代码中,您可以通过索引访问每个参数,例如
String firstParameter = params[0];
String secondParameter = params[1];
更新
您还可以更改方法的签名以接受任何对象作为参数,例如
public interface ITask<T> {
T execute(Object ... params) throws RemoteException, SQLException;
}
但是,您必须将每个参数显式转换为 Object 类型,例如
String firstParameter = (String) params[0];
Integer secondParameter = (Integer) params[1];
推荐阅读
- nginx - 当我在代理服务器中使用 expires 时,代理忽略标头不起作用
- multithreading - 将结构作为 P 线程参数传递 Linux 无法转换为指针类型
- javascript - 使用按钮更改 textarea 值的问题(vanilla JS)
- python - 重复KFold & cross_val_predict
- r - 最后的观察结果向前添加
- python - 如何合并多个数据框并将它们显示在 python 的一个箱线图中?
- java - 在 Android 中以编程方式连接到 Wifi AP
- r - 检查日期是否在R中的间隔内非常慢
- ruby-on-rails - 我如何在 Rails 6 的 csv 文件中导出/导入头像(使用活动存储)
- amazon-web-services - Cloudformation 到 SSM 参数的 terraform 转换