Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does groovy add new methods to Java classes?

Tags:

groovy

Consider the following snippet -

println String.class

The output is -

class java.lang.String

I was expecting some subclass of String since it contains many members that are not a part of the Java class. For example -

println String.methods.size()

methods is not a member of the Java class.

How does this magic happen?

like image 234
Kshitiz Sharma Avatar asked Jul 30 '13 12:07

Kshitiz Sharma


People also ask

How do you call a method in Groovy class?

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.

Can I use Java classes in Groovy?

Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.

How do I create a method in Groovy?

A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It's not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added.


1 Answers

Groovy has a metaclass registry. When you call a method on a class the registry is inspected to see if a metaClass extension method exists for that class instance.

From the standard documentation -

Each groovy object has a metaClass that is used to manage the dynamic nature of the language. This class intercepts calls to groovy objects to ensure that the appropriate grooviness can be added. Source

like image 146
tim_yates Avatar answered Sep 18 '22 01:09

tim_yates