gpt4 book ai didi

java - 如何在多个类中抽象出具有不同返回类型的相同方法

转载 作者:行者123 更新时间:2023-12-02 01:22:58 25 4
gpt4 key购买 nike

如果我没有提前正确提出问题,我深表歉意。

我有大约 15 个相关的类,它们使用相同的代码但返回类型不同。我如何将其抽象出来以避免所有这些类中的代码重复?

    public ChargeResponse findByTransactionId(final String txId) {
ChargeResponse chargeResponse = null;
try (Connection connection = dataSource.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement(VIEW_SERVICE_TRANSACTION_CHARGE_QUERY);
preparedStatement.setString(1, txId);
final ResultSet resultSet = preparedStatement.executeQuery();
chargeResponse = parseQueryResults(resultSet);

} catch (SQLException e) {
e.printStackTrace();
}
return chargeResponse;
}
    public EventsResponse findByTransactionId(final String txId) {
EventsResponse eventsResponse = null;
try (Connection connection = dataSource.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement(VIEW_SERVICE_TRANSACTION_EVENTS_QUERY);
preparedStatement.setString(1, txId);
final ResultSet resultSet = preparedStatement.executeQuery();
eventsResponse = parseQueryResults(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
return eventsResponse;
}

等等..

最佳答案

public <T> T findByTransactionId(final String txId) {
T chargeResponse;
try (Connection connection = dataSource.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement(VIEW_SERVICE_TRANSACTION_CHARGE_QUERY);
preparedStatement.setString(1, txId);
final ResultSet resultSet = preparedStatement.executeQuery();
chargeResponse = parseQueryResults(resultSet);

} catch (SQLException e) {
e.printStackTrace();
}
return chargeResponse;
}

对 parseQueryResults 执行相同的操作。然后将这些方法移至父类。

关于java - 如何在多个类中抽象出具有不同返回类型的相同方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com