JN3535-Reflection Add comment to Wiki View in Wiki Edit Wiki page Printable Version

We can examine classes in Groovy to find out information in the form of strings.

Examining Classes

To find out a class's name and superclasses:

To examine the interfaces:

We can check if a class is a class or an interface:

We can examine public fields and their types:

We can look at a certain field of a class:

We can also look at the constructors and methods of a class:

Some code to find out all the getters for a class:

To see all nested classes for a particular class (eg, of Character):

To query a particular nested class (eg, Character.UnicodeBlock):

Reflecting the Reflection classes themselves

We can use reflection on the reflection classes themselves. For example:

We can look at the modifiers of methods and classes:

Manipulating Objects

When a class is unknown at compile time (eg, we only have a string representation of a class name), we can use reflection to create objects:

We can examine and change public fields for a class refering using a String for the name:

And we can call methods using a string for the name:

Working with Arrays

We can examine and manipulate arrays. To enquire the public array fields of a class:

To enquire the component type/s of an array:

We can create and copy arrays when their component type and size is unknown at compile time:

We can create multi-dimensional arrays in a similar way, where component type and array sizes can be unknown at compile time:

We can use set() and get() to copy the contents of one array index to another:

This tutorial is loosely based on Sun's tutorial on Java Reflection, but using Groovy code instead.

 

Search

Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified