Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Groovy String class

Groovy allows to do some nice things with strings in frontend pages, like:

${"hello".capitalize()}

How can I add a new custom method to the String class? Like:

${"hello".custom()}

like image 215
Mark Avatar asked Apr 27 '12 20:04

Mark


People also ask

Can String class be extended?

You cannot extend a class that is marked as final. You can use composition to either put a String object inside or you can hand roll your own version. This can be accomplished via character arrays and the other magic that goes into creating String classes.

Can a Groovy class extend a Java class?

Yes, you may intermix Java and Groovy sources in a project and have source dependencies in either direction, including "extends" and "implements".

How do you call a class in Groovy?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.


1 Answers

Use the metaClass

String.metaClass.custom = { //dosomething }

See http://www.groovyexamples.org/2010/07/19/dynamically-add-properties-to-a-class/

like image 160
MarcDeXeT Avatar answered Oct 20 '22 17:10

MarcDeXeT