Can I override the string length?

I would like to reimplement the Java class method. For example, for "hi".length() to return 4 . (How can I do it?

I know using SomeClass.metaClass I can get a reference to an existing method and define a new (or overriding) method, but I don't seem to be able to do this for existing Java methods.

+7
string groovy
source share
3 answers

It seems like it's possible with the abuse of String metaClass . But the attempt that I have made so far in the groovy console has not led to the expected result:

 def oldLength = String.metaClass.length String.metaClass.length = { -> return oldLength+10; } println "hi".length() 

displays sad 2

I think you could take a look at Proxy MetaClass or Delegating a Metaclass .

+2
source share

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 
+4
source share

If you redefine it, it will only work in Groovy code. Groovy cannot change the way Java code is executed.

In Groovy, "hi".length() roughly equivalent to this Java:

 stringMetaClass.invokeMethod("hi","length"); 

Since Groovy does not actually call a straight length, metaClass tricks work in Groovy code. But Java does not know about MetaClasses, so there is no way to do this work.

+1
source share

All Articles