如何避免代码重复导致的重载?

The*_*ion 0 java hash

我试图将名称,哈希密码,盐和哈希类型插入数据库.唯一改变的是参数的类型.我相信它可以更有效地完成.如何避免使用重载?我需要使用泛型吗?谢谢.

InsertMethods

protected void insert(String name, String secretpassword, String salt, String type)
{
    String sql = "INSERT INTO login(username,password,salt,type) VALUES(?,?,?,?)";

    try (Connection conn = this.connect();
         PreparedStatement pstmt = conn.prepareStatement(sql)) {
        pstmt.setString(1, name);
        pstmt.setString(2, secretpassword);
        pstmt.setString(3, salt);
        pstmt.setString(4, type);
        pstmt.executeUpdate();
        System.out.println("Successful");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
}

protected void insert(String name, byte[] secretpassword, String salt, String type)
{
    String sql = "INSERT INTO login(username,password,salt,type) VALUES(?,?,?,?)";

    try (Connection conn = this.connect();
         PreparedStatement pstmt = conn.prepareStatement(sql)) {
        pstmt.setString(1, name);
        pstmt.setString(2, Arrays.toString(secretpassword));
        pstmt.setString(3, salt);
        pstmt.setString(4, type);
        pstmt.executeUpdate();
        System.out.println("Successful");
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

Rus*_*lan 6

您可以从第二个方法调用第一个方法,如:

protected void insert(String name, byte[] secretpassword, String salt, String type)
{
    insert(name, Arrays.toString(secretpassword), salt, type);
}
Run Code Online (Sandbox Code Playgroud)