To try to forestall any concern, this is for a personal project. I'm more interested in learning about the internals of the jvm than I am in hearing about what a horrible idea this is :)
Normally, java does not allow you to implement a generic interface multiple times with different generic parameters.
For example, the following code will not compile:
interface Foo<T>
{ ... }
interface MyFoo
extends Foo<MyObject>
{ ... }
final class CannotDoThis<T>
implements Foo<T>,
MyFoo // Error: Foo cannot be inherited with different arguments
{ ... }
However, I was wondering if there was a way to get around this restriction. For example:
interface Supplier<T>
{ T get(); }
interface MySupplier
extends Supplier<MyObject>
{ }
final class NullSupplier<T>
implements Supplier<T>,
MySupplier // Still an error...
{ public T get() { return null; } } // ...but after erasure this should be safe
I found that by manually disassembling and reassembling the bytecode for NullSupplier.class
, I was able to forcibly implement the MySupplier
interface on NullSupplier
. When I add the patched class file to the resources directory for my project, it seems to compile and run without issue.
Are there any runtime issues that could arise from rewriting the bytecode in such a manner?
One oddity that immediately sticks out to me is that MySupplier.get
should have a return type of MyObject
whereas the return type of NullSupplier.get
is Object
. However, this doesn't seem to stop the code from executing properly (I wouldn't expect a ClassCastException
, but I was surprised that there weren't any classloader errors).