Professional Documents
Culture Documents
and Reflection
What is RTTI?
1
Downcasting
getCorners()
2
The Class class.
3
Accessing Class objects (II).
4
An example of RTTI.
An example of RTTI.
// main() method,
// continues from the previous slide
try {
for(int i = 0; i < shapes.length; i++) {
int rnd = 1 + rand.nextInt(shapeTypes.length - 1);
shapes[i] = shapeTypes[rnd].newInstance();
shapeTypes[rnd].isInstance(shapes[i]); // always true!
}
} catch(InstantiationException e) {
System.out.println("Cannot instantiate");
System.exit(1);
} } }
5
An example of RTTI.
// main() method,
// continues from the previous slide
try {
for(int i = 0; i < shapes.length; i++) {
int rnd = 1 + rand.nextInt(shapeTypes.length - 1);
shapes[i] = shapeTypes[rnd].newInstance();
shapeTypes[rnd].isInstance(shapes[i]);
}
} catch(InstantiationException e) {
System.out.println("Cannot instantiate");
System.exit(1);
} } }
6
Class Names
RTTI limitation
The Java RTTI mechanism allows you to discover
an objects type at run time. However:
it requires full knowledge of the needed
types at compile time.
7
Reflection
java.lang.reflect overview
8
An example of reflection.
An example of reflection.
9
Discovering modifiers.
Class c = x.getClass();
// returns the modifiers flags:
int m = c.getModifiers();
// they have to be checked with the following methods:
Modifier.isPublic(m);
Modifier.isAbstract(m);
Modifier.isFinal(m);
Discovering fields.
Class c = x.getClass();
Fields[] fields = c.getFields();
for (int i = 0; i < fields.length; i++) {
// gets the name:
String name = fields[i].getName();
// gets the type:
Class type = fields[i].getType();
}
10
Invoking constructors.
The newInstance() method of Class, works
through reflection, and can be used also in
case a class is available only at run time.
However, it only works for constructors without
arguments. Otherwise a Constructor object
has to be used. E.g:
// NOTE: exception handling has been omitted for brevity!
// assume Square has the ctor Square(int size)
// first we get the constructor with specified arguments:
Class[] argsClass = new Class[] {int.class};
Integer size = new Integer(10);
Constructor ctor = Square.class.getConstructor(argsClass);
// then we invokes the constructor with arguments:
Object[] args = new Object[] {size};
Object o = ctor.newInstance(args);
Invoking methods.
11
Conclusions.
RTTI:
• It requires type information (.class files) at
compile time
Reflection:
• It requires type information at run time
References
12