I'm trying to write a generic method that looks like this:
private static <T> Class<? extends T> immutableVersionOfClass(Class<T> clazz) {
return new ByteBuddy()
.subclass(clazz)
.method(not(returns(VOID)))
.intercept(to(GetterInterceptor.class))
.method(returns(VOID))
.intercept(to(SetterInterceptor.class))
.make()
.load(clazz.getClassLoader())
.getLoaded();
}
but when final class is passed as an argument I get an exception:
java.lang.IllegalArgumentException: Cannot subclass primitive, array or final types
I'd like my method to be able to subclass also final classes. Is there any workaround for this problem?
There is no way to subclass a final class. It's forbidden by the language spec.
ByteBuddy largely respects the language specification, so even if you wanted to extend a final class, you couldn't unless you were able to manipulate the byte code of the class you wanted to override to be not
final
, although at that point you're messing with things you really shouldn't be.