为适用于 JDBC 3 和 4 的 java.sql.Connection 创建一个包装器

2022-01-24 00:00:00 connection jdbc java

是否有一些技巧可以为 java.sql.Connection 创建一个适用于 JDBC 3 和 4 的包装器(Sun 在 JDBC 4 的接口中添加了一些方法和新类型)无需在编译时修补源代码的东西?

Is there some hack to create a wrapper for java.sql.Connection which works with JDBC 3 and 4 (Sun added a couple of methods and new types to the interface for JDBC 4) without resorting to something which patches the source at compile time?

我的用例是我需要生成一个适用于 Java 5 和 6 的库,我真的很想避免创建它的两个版本.

My use case is that I need to generate a library which works with Java 5 and 6 and I'd really like to avoid creating two versions of it.

推荐答案

没试过,应该可以.

创建您的类以实现 Java 6 版本.java.sql 中的新类(NClob、SQLXML、SQLClientInfoException)会有问题.假设您不使用这些类(因为您也在使用 Java 5),请创建它们的虚拟实现并将其放入单独的 jar 中.在 Java 5 部署中,使用 引用此 jar-Xbootclasspath 命令行变量,以便正确加载它们.

Create your class to implement the Java 6 version. It will have problem with the new classes in java.sql (NClob, SQLXML, SQLClientInfoException). Assuming you do not use these classes (as you are working with Java 5 as well), create a dummy implementation of them and put it in a separate jar. In the Java 5 deployment, refer to this jar with the -Xbootclasspath command line variable so they will be loaded correctly.

请注意,您的包装器需要知道它是在 Java 5 还是 6 上运行(以便正确委托),因此您可能希望在一个单独的类中处理所有 Java 6 功能,并在运行时实例化(参见 state 设计模式)

Notice that your wrapper will need to know whether it is running on Java 5 or 6 (in order to delegate properly), so you will probably want to have all the Java 6 features handled in a separate class, instantiated in run time (see the state design pattern)

相关文章