Lecture8 JavaReflection
Lecture8 JavaReflection
and Reengineering
LECTURE 8
The Java Core Reflection
Note:
The examples used in these slides are taken from:
class SampleModifier {
public static void main(String[] args) {
String s = new String();
printModifiers(s);
}
class SampleSuper {
class SampleInterface {
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(); //returns all the accessible
//public fields of c
for (int i = 0; i < publicFields.length; i++) {
String fieldName = publicFields[i].getName(); //gets the field’s name
Class typeClass = publicFields[i].getType(); //gets the field’s type
String fieldType = typeClass.getName(); //gets the type’s name
System.out.println("Name: " + fieldName +
", Type: " + fieldType);
}
}
}
class SampleConstructor {
class SampleSet {
public static void main(String[] args) {
Rectangle r = new Rectangle(100, 20);
System.out.println("original: " + r.toString());
modifyWidth(r, new Integer(300));
System.out.println("modified: " + r.toString());
}
class SampleNoArg {