java 8 lambda方法在try-with-resources

时间:2015-12-06 21:26:44

标签: lambda java-8

Java 8 lambdas包装此

的正确语法是什么
catch (Exception e) {
        throw JiraUtils.convertException(e);
}

并且不要在需要此JiraRestClient的所有方法中重复它?

@Override
public GTask loadTaskByKey(String key, Mappings mappings) throws ConnectorException {
    try(JiraRestClient client = JiraConnectionFactory.createClient(config.getServerInfo())) {
        final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
        return loader.loadTask(key);
    } catch (Exception e) {
        throw JiraUtils.convertException(e);
    }
}

@Override
public List<GTask> loadData(Mappings mappings, ProgressMonitor monitorIGNORED) throws ConnectorException {
    try(JiraRestClient client = JiraConnectionFactory.createClient(config.getServerInfo())) {
        final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
        return loader.loadTasks(config);
    } catch (Exception e) {
        throw JiraUtils.convertException(e);
    }
}

注意:删除catch()块会导致编译错误:

unreported exception java.io.IOException; must be caught or declared to be thrown
  exception thrown from implicit call to close() on resource variable 'client'

这是link to JiraRestClient

1 个答案:

答案 0 :(得分:2)

你可以这样做:

@Override
public GTask loadTaskByKey(String key, Mappings mappings) throws ConnectorException {
  return withJiraRestClient(client -> {
    final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
    return loader.loadTask(key);
  });
}

@Override
public List<GTask> loadData(Mappings mappings, ProgressMonitor monitorIGNORED) throws ConnectorException {
  return withJiraRestClient(client -> {
    final JiraTaskLoader loader = new JiraTaskLoader(client, config.getPriorities());
    return loader.loadTasks(config);
  });
}

private <T> T withJiraRestClient(JiraRestClientAction<T> f) throws ConnectorException {
  try (JiraRestClient client = JiraConnectionFactory.createClient(config.getServerInfo())) {
    return f.apply(client);
  } catch (IOException e) {
    throw JiraUtils.convertException(e);
  }
}

@FunctionalInterface
interface JiraRestClientAction<T> {
  T apply(JiraRestClient client) throws IOException;
}