Search code examples
javaapache-commons-dbcp

Class that implements an interface in a jar, but does not override the methods


My project has a dependency to apache commons-dbcp and we are using version 1.2.2

The commons-dbcp version we are using has the class org.apache.commons.dbcp.BasicDataSource which implements javax.sql.DataSource which in turn implements java.sql.Wrapper, however BasicDataSource does not implement the methods defined in Wrapper (jdk 1.6.x). But my project which has a class (MyClass) that extends BasicDataSource compiles without any problems - I am a bit puzzled here. In IntelliJ, I see MyClass as an error though.


Solution

  • That class has been compiled with an earlier version of the javax.sql.DataSource interface (the Java 5 or earlier version). The Wrapper interface was introduced with Java 6 / JDBC 4.0.

    When the classloader loads a class that implements an interface, but doesn't implement all the new methods, it allows it. When the method is actually called, a NoSuchMethodError is thrown (I believe it stubs the missing methods to throw this exception). This allows for - limited - forward compatibility: as long as that method isn't actually called the implementation will work.

    This also means that when you subclass this class it will behave as if all methods have been implemented (even if they weren't), as long as the source of that class isn't part of your project.