Java中ITask接口的execute方法如何实现动态接收自定义参数?
改造方案
核心需求为让execute方法支持任意数量、类型的入参,有三种主流实现方式,对应不同的场景和取舍:
方案1:类型安全的双泛型接口改造(推荐)
通过增加入参泛型实现编译期的参数类型校验,适合绝大多数业务场景:
// 改造后的ITask接口,I为入参类型,T为返回值类型 public interface ITask<I, T> { T execute(I input) throws RemoteException, SQLException; }
同步改造IRMI接口及实现:
public interface IRMI extends Remote { <I, T> T executeTask(ITask<I, T> t, I input) throws SQLException, RemoteException; } @Override public <I, T> T executeTask(ITask<I, T> t, I input) throws SQLException, RemoteException { return t.execute(input); }
多参数场景可以用JDK16+的record定义入参结构体(低版本用普通POJO类即可):
// 定义创建用户任务的入参结构 public record CreateUserParam(String username, String password, String email) {} // 实现CreateUser任务类 public class CreateUser implements ITask<CreateUserParam, Void> { @Override public Void execute(CreateUserParam input) throws RemoteException, SQLException { // 业务逻辑直接读取input的属性即可 return null; } }
调用示例:
public void registerUserTask() throws SQLException, RemoteException { new CreateUser().execute(new CreateUserParam(username, password, email)); // 走RMI调用的写法:irmi.executeTask(new CreateUser(), new CreateUserParam(username, password, email)); }
方案2:可变参数实现(灵活但无编译期校验)
如果不想单独定义入参类,追求极致灵活度,可以把execute改成接收可变Object参数:
public interface ITask<T> { T execute(Object... args) throws RemoteException, SQLException; }
同步改造IRMI接口及实现:
public interface IRMI extends Remote { <T> T executeTask(ITask<T> t, Object... args) throws SQLException, RemoteException; } @Override public <T> T executeTask(ITask<T> t, Object... args) throws SQLException, RemoteException { return t.execute(args); }
CreateUser实现类:
public class CreateUser implements ITask<Void> { @Override public Void execute(Object... args) throws RemoteException, SQLException { // 自行做参数校验和类型转换 if (args.length != 3) throw new IllegalArgumentException("参数数量错误"); String username = (String) args[0]; String password = (String) args[1]; String email = (String) args[2]; // 执行业务逻辑 return null; } }
该方案可以完全匹配你期望的调用写法:
public void registerUserTask() throws SQLException, RemoteException { new CreateUser().execute(username, password, email); }
缺点是没有编译期类型校验,参数传错类型/数量只有运行时才能发现,仅适合参数场景非常少的情况使用。
方案3:构造器传参(无侵入现有接口)
如果你不能修改现有ITask的无参execute定义,可以把参数通过任务类的构造器传入:
public class CreateUser implements ITask<Void> { private final String username; private final String password; private final String email; public CreateUser(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } @Override public Void execute() throws RemoteException, SQLException { // 直接读取成员变量执行业务逻辑 return null; } }
调用示例:
public void registerUserTask() throws SQLException, RemoteException { new CreateUser(username, password, email).execute(); }
内容的提问来源于stack exchange,提问作者kandre
相关产品推荐
相关产品推荐

