John
John

Reputation: 4006

How to make an interface more specific in Java?

I have a large system that uses two different sql databases. I have very many places where both databases are included in a method. For example:

public static void doSomething(Connection mySqlConn, Connection dbConn) {...}

Is there a simple (elegant) way to make the signature more specific. For example:

public static void doSomething(MySqlConnection mySqlConn, DatabricksSqlConnection dbConn {...}

I tried to extend the Connection interface and then cast the connection to this interface but this gives a cannot cast exception (the widening of the interface is not allowed).

More specific interface

import java.sql.Connection;

public interface MySqlConnection extends Connection {

}

This throws an exception

public static MySqlConnection getMysqlConnection(String schema, String url, String uid, String pwd) {
    try {
        Connection conn = DriverManager.getConnection(url, uid, pwd);
        return (MySqlConnection) conn;
    } catch (Exception exp) {
        throw new RuntimeException(exp);
    }

}

Upvotes: 1

Views: 171

Answers (2)

ziggystar
ziggystar

Reputation: 28680

This is not a direct answer to the question, but might solve your problem in a different way:

You can create a class that holds both Connections as named members and then you can pass objects of this class instead of the two connections separately.

Upvotes: 2

Bernd Farka
Bernd Farka

Reputation: 512

You are misusing the concepts of the DriverManager with this usecase.

The DriverManager is here to help you not introducing any Vendor Specific APIs when you are dealing with JDBC objects.

Your MySql JDBC driver already contains a dedicated Implemenation of the MySQL bundled (which an be instantiated by hand). There is already a com.mysql.jdbc.Connection Interface (which you could cast) and a com.mysql.jdbc.ConnectionImpl you could try to instantiate by yourself.

But this is not considered as good Practice at all.

Most probably a Factory or Holder object for you different Data Base Connections is the thing which could help you.

Upvotes: 1

Related Questions