接口
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
,则可以将执行方法更改为:
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];