Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I redefine String#length?

Tags:

string

groovy

I'd like to re-implement a method of a Java class. For example, for "hi".length() to return 4. (How) Can I do that?

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

like image 811
IttayD Avatar asked Aug 23 '10 13:08

IttayD


People also ask

Can you modify a string?

According to java, you are only not allowed to change the string object, but you can still modify that object. There are several ways by which you can create a string object and hence declare a string. But for now, we take the simplest way to declare the string, which is as follows; String S= “Hello”;.

Can you redefine a string in C?

You need to copy the string into another, not read-only memory buffer and modify it there. Use strncpy() for copying the string, strlen() for detecting string length, malloc() and free() for dynamically allocating a buffer for the new string. Show activity on this post. The malloc needs 1 more byte.

Can you modify a string in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

Can you reassign a string python?

Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to represent computed values.


1 Answers

Using Groovy, you can replace any method (even those of final classes) with your own implementation. Method replacement in Groovy uses the meta-object protocol, not inheritance.

Here's 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
like image 140
Dónal Avatar answered Sep 20 '22 02:09

Dónal