首页 > 解决方案 > 使用 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);
    }

标签: java

解决方案


您必须将execute方法参数从现在的无参数更改为参数数组。

例如,如果您知道需要传递的所有参数都是Strings,您可以将执行方法更改为:

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];

推荐阅读