Java Reference
In-Depth Information
Declared Fields for com.jdojo.reflection.Person
private int id
private String name
Accessible Fields for com.jdojo.reflection.Person
■
You cannot use this technique to describe the
length
field of an array object. each array type has a corresponding
class. When you try to get the fields of an array class using the
getFields()
method, you get an array of
Field
objects
of zero length. the array length is not part of the array's class definition. rather, it is stored as part of the array object in
the object header. for more information on array's
length
field, please refer to Chapter 11.
Tip
Reflecting on an Executable
An instance of the
Method
class represents a method. An instance of the
Constructor
class represents a constructor.
Structurally, methods and constructors have few things in common. Both use modifiers, parameters, and throws
clause. Java 8 refactored these classes to inherit them from a common abstract superclass,
Executable
. Methods to
retrieve information common to both have been added/moved to the
Executable
class.
A parameter in an
Executable
is represented by an object of the
Parameter
class, which was added in Java 8. The
getParameters()
method in the
Executable
class returns all parameters of an
Executable
as an array of
Parameter
.
By default, the formal parameter names are not stored in the class files to keep the file size smaller. The
getName()
method of the
Parameter
class returns synthesized parameter names like arg0, arg1, etc. unless the actual parameter
names are retained. If you want to retain the actual parameter names in class files, you need to compile the source
code using the
-parameters
option with the
javac
compiler.
The
getExceptionTypes()
method of the
Executable
class returns an array of
Class
objects, which describes the
exceptions thrown by the
Executable
. If no exceptions are listed in the
throws
clause, it returns an array of length zero.
The
getModifiers()
method of the
Executable
class returns the modifiers as an
int
.
The
getTypeParameters()
method of the
Executable
class returns an array of
TypeVariable
that represents the
type parameters for generic methods/constructors. The examples in this chapter will not include the generic type
variable declarations in method/constructors.
Listing 3-6 contains a utility class that consists of static methods to get information about an
Executable
such as
the list of modifiers, parameters, and exception. I will use the class when I discuss methods and constructors in the
subsequent sections.
Listing 3-6.
A Utility Class to Get Information for an Executable
// ExecutableUtil.java
package com.jdojo.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.ArrayList;