Using Groovy, you can replace any method (even those from the final classes) with your own implementation. Groovy's method override uses a meta-object protocol, not inheritance.
Here is the example you requested, i.e. how to make String.length() always return 4
// Redefine the method String.metaClass.invokeMethod = { name, args -> def metaMethod = delegate.metaClass.getMetaMethod(name, args) def result = metaMethod.invoke(delegate, args) name == 'length' ? 4 : result } // Test it assert "i_do_not_have_4_chars".length() == 4
Dรณnal
source share