Java : Wrapper (JDBC) with Examples

Wrapper (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Wrapper methods.


Summary

Interface for JDBC classes which provide the ability to retrieve the delegate instance when the instance in question is in fact a proxy class.

Class diagram

Note :

  • The code examples in this page use Apache Derby as the JDBC driver. Apache Derby was once included in older JDKs, but is not included in the latest JDK.
final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {

    final var iface = EmbedConnection.class;
    System.out.println("iface = " + iface);

    if (connection.isWrapperFor(iface)) {
        System.out.println("isWrapperFor = true");

        final EmbedConnection unwrapped = connection.unwrap(iface);
        System.out.println("unwrapped = " + unwrapped);
    }
}

// Result
// ↓
//iface = class org.apache.derby.impl.jdbc.EmbedConnection
//isWrapperFor = true
//unwrapped = org.apache.derby.impl.jdbc.EmbedConnection@626393072
//  (XID = 166), (SESSIONID = 1), (DATABASE = memory:db), (DRDAID = null)

Methods

boolean isWrapperFor (Class<?> iface)

Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an object that does.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {

    final var iface = EmbedConnection.class;
    System.out.println("iface = " + iface);

    if (connection.isWrapperFor(iface)) {
        System.out.println("isWrapperFor = true");

        final EmbedConnection unwrapped = connection.unwrap(iface);
        System.out.println("unwrapped = " + unwrapped);
    }
}

// Result
// ↓
//iface = class org.apache.derby.impl.jdbc.EmbedConnection
//isWrapperFor = true
//unwrapped = org.apache.derby.impl.jdbc.EmbedConnection@626393072
//  (XID = 166), (SESSIONID = 1), (DATABASE = memory:db), (DRDAID = null)

<T> T unwrap (Class<T> iface)

Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy.

final var url = "jdbc:derby:memory:db;create=true";
try (final var connection = DriverManager.getConnection(url)) {

    final var iface = EmbedConnection.class;
    System.out.println("iface = " + iface);

    if (connection.isWrapperFor(iface)) {
        System.out.println("isWrapperFor = true");

        final EmbedConnection unwrapped = connection.unwrap(iface);
        System.out.println("unwrapped = " + unwrapped);
    }
}

// Result
// ↓
//iface = class org.apache.derby.impl.jdbc.EmbedConnection
//isWrapperFor = true
//unwrapped = org.apache.derby.impl.jdbc.EmbedConnection@626393072
//  (XID = 166), (SESSIONID = 1), (DATABASE = memory:db), (DRDAID = null)

Related posts

To top of page