Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Current »

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.

  • No labels