Transcript Class

Java reflections API
Lecture 1
1
Assignments

Java 1.4 or Java 1.5?
• Both are ok, but the assignments are written
for Java 1.4, and specific Java 1.5 support
may not be prioritized.
2
Run-time introspection






If you are writing a class browser, debug system, IDE
environment (Eclipse).
Discover which methods/constructors are available in
an object or class.
Discover attributes/fields
Discover super classes and implemented interfaces
Instantiate objects from class name
And more…
3
Getting the “Class object”


Taste on it… confused?
An object that represents a class…
•
•
•
For each class, the Java Runtime Environment (JRE)
maintains an immutable Class object that contains
information about the class.
A Class object represents, or reflects, the class.
Class objects not only represent classes but also
interfaces.
4
Confusion continued…
5
Examples


If an instance of the class is available…
• Class
c = mystery.getClass();
retrieve the Class object for the superclass
• TextField
t = new TextField();
Class c = t.getClass();
Class s = c.getSuperclass();


If you know the name of the class at compile time,
• Class
c = java.awt.Button.class;
If the class name is unknown at compile time, but
available at runtime
• Class
c = Class.forName(strg);
6
Getting the Class Name

import java.awt.Button;
class SampleName {
public static void main(String[] args) {
Button b = new Button();
printName(b);
}
static void printName(Object o) {
Class c = o.getClass();
String s = c.getName();
System.out.println(s);
}

}
What will be printed?
7
Discovering Class Modifiers



public final class Coordinate {int x, int y, int z}
class SampleModifier {
public static void main(String[] args) {
String s = new String();
printModifiers(s);
}
public static void printModifiers(Object o) {
Class c = o.getClass();
int m = c.getModifiers();
if (Modifier.isPublic(m))
System.out.println("public");
if (Modifier.isAbstract(m))
System.out.println("abstract");
if (Modifier.isFinal(m))
System.out.println("final");
}
}
Output?
8
Finding the superclass

To determine the superclass of a class,
you invoke the getSuperclass method.
• This method returns a Class object
representing the superclass, or returns null if
the class has no superclass. To identify all
ancestors of a class, call getSuperclass
iteratively until it returns null.
9
Example

import java.lang.reflect.*;
import java.awt.*;
class SampleSuper {
public static void main(String[] args) {
Button b = new Button();
printSuperclasses(b);
}
}
static void printSuperclasses(Object o) {
Class subclass = o.getClass();
Class superclass = subclass.getSuperclass();
while (superclass != null) {
String className = superclass.getName();
System.out.println(className);
subclass = superclass;
superclass = subclass.getSuperclass();
}
}
10
Interfaces

An interface is similar to a superclass
and is thus as important as such. The
class below implements two interfaces.
•public
class RandomAccessFile
implements DataOutput, DataInput
11
Example
class SampleInterface {
public static void main(String[] args) {
try {
RandomAccessFile r=new RandomAccessFile("fil", "r");
printInterfaceNames(r);
} catch (IOException e) {
System.out.println(e);
}
}
}
static void printInterfaceNames(Object o) {
Class c = o.getClass();
Class[] theInterfaces = c.getInterfaces();
for (int i = 0; i < theInterfaces.length; i++) {
String interfaceName = theInterfaces[i].getName();
System.out.println(interfaceName);
}
}
12
Examining Interfaces

The isInterface() method helps in
distinguishing between interfaces and
classes.
13
Example

class SampleCheckInterface {
public static void main(String[] args) {
Class observer = Observer.class;
Class observable = Observable.class;
verifyInterface(observer);
verifyInterface(observable);
}
static void verifyInterface(Class c) {
String name = c.getName();
if (c.isInterface()) {
System.out.println(name + " is an interface.");
} else {
System.out.println(name + " is a class.");
}
}

}
Output?
14
Identifying Class Fields

You might want to find out what fields
belong to a particular class, by invoking
the getFields() method on a Class
object.
15
Example

class SampleField {
public static void main(String[] args) {
GridBagConstraints g = new GridBagConstraints();
printFieldNames(g);
}
}
static void printFieldNames(Object o) {
Class c = o.getClass();
Field[] publicFields = c.getFields();
for (int i = 0; i < publicFields.length; i++) {
String fieldName = publicFields[i].getName();
Class typeClass = publicFields[i].getType();
String fieldType = typeClass.getName();
System.out.println("Name: " + fieldName +
", Type: " + fieldType);
}
}
16
Is the field an array?

Use the Class.isArray() method.

Field[] publicFields = targetClass.getFields();
for (int i = 0; i < publicFields.length; i++) {
String fieldName = publicFields[i].getName();
Class typeClass = publicFields[i].getType();
String fieldType = typeClass.getName();
if (typeClass.isArray()) {
System.out.println("Name: " + fieldName +
", Type: " + fieldType);
}
}
17
Retrieving Component Types


Integer[] is an array with component type
Integer
The component type of a
multidimensional array is an array.
• Integer[][] m = new Integer[10][10];
• In the line above the component type of m
is…
• Integer[]
18
Class Constructors


Information about constructors is
retrieved by calling the getConstructors()
method.
Returns an Array of Constructor objects
19
Example
class SampleConstructor {
public static void main(String[] args) {
Rectangle r = new Rectangle();
showConstructors(r);
}
}
static void showConstructors(Object o) {
Class c = o.getClass();
Constructor[] theConstr = c.getConstructors();
for (int i = 0; i < theConstr.length; i++) {
System.out.print("( ");
Class[] parameterTypes = theConstr[i].getParameterTypes();
for (int k = 0; k < parameterTypes.length; k++) {
String parameterString = parameterTypes[k].getName();
System.out.print(parameterString + " ");
}
System.out.println(")");
}
}
20
Methods

Methods are retrieved in a similar
manner, in an Array.
21
Manipulating Objects

With the reflection API you may also
• Create objects and Arrays of objects
• Get and set field values
• Invoke methods
22
“Real Life” Example from the
IFOR navigation project

Ini file:

load.rangearrayproxy = com.ifor.proxy.RangeArrayProxy
load.tycoradararrayproxy1 = com.ifor.proxy.RangeArrayProxy
load.tycoradararrayproxy2 = com.ifor.proxy.RangeArrayProxy
load.map2dproxy = com.ifor.proxy.Obstacle2DProxy



23
Example cont.
Java:
public Loadable loadableFactory(String className) {
Loadable object = null;
try
{
Class classDefinition = Class.forName(className);
object = (Loadable)classDefinition.newInstance();
}
catch (IllegalArgumentException ex)
{ logger.log(this, "className + "
catch (InstantiationException ex)
{ logger.log(this, "className + "
catch (IllegalAccessException ex)
{ logger.log(this, "className + "
catch (ClassNotFoundException ex)
{ logger.log(this, "className + "
}
" + ex, Logger.EXCEPTION);}
" + ex, Logger.EXCEPTION);}
" + ex, Logger.EXCEPTION);}
" + ex, Logger.EXCEPTION);}
return object;
24
Reflection classes

The 7 classes that compose the reflection API:
•
•
•
•
•
•
•

Object: Provides the getClass() method.
Class: Reflects Classes and Interfaces.
Array: Provides static methods to dynamically create and access
arrays.
Constructor: Allows you to instantiate a class dynamically.
Field: Allows you to invoke the method dynamically.
Method: Provides access to a single method on a class or
interface
Modifier: Allows you to get information about the access modifiers
of a class and its members.
Object and Class are part of the java.lang package, while the
rest is part of java.lang.reflect package.
25