I
Ian A. Mason
I'm designing an application and was thinking of using reflection, but
a simple experiment failed. Here it is. I'm reading Dale Green's
chapter in the Java Tutorial, and I copy his simplest example of
constructing an object using a no arg constructor, and modify it
slightly to reflect the types of things I'm interested in
(java.awt.Shape) and in particular the 2D versions:
import java.lang.reflect.*;
import java.awt.*;
import java.awt.geom.*;
class SampleNoArg {
public static void main(String[] args) {
Rectangle2D.Float r =
(Rectangle2D.Float)createObject("java.awt.geom.Rectangle2D.Float");
System.out.println(r.toString());
}
static Object createObject(String className) {
Object object = null;
try {
Class classDefinition = Class.forName(className);
object = classDefinition.newInstance();
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
return object;
}
}
and I discover it can't find the class by that name. I also notice that
nested classes don't seem to be mentioned in the refection API
(i.e they don't qualify as members). So should I give up, or is there
a way to make such beasts using reflection.
a simple experiment failed. Here it is. I'm reading Dale Green's
chapter in the Java Tutorial, and I copy his simplest example of
constructing an object using a no arg constructor, and modify it
slightly to reflect the types of things I'm interested in
(java.awt.Shape) and in particular the 2D versions:
import java.lang.reflect.*;
import java.awt.*;
import java.awt.geom.*;
class SampleNoArg {
public static void main(String[] args) {
Rectangle2D.Float r =
(Rectangle2D.Float)createObject("java.awt.geom.Rectangle2D.Float");
System.out.println(r.toString());
}
static Object createObject(String className) {
Object object = null;
try {
Class classDefinition = Class.forName(className);
object = classDefinition.newInstance();
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
return object;
}
}
and I discover it can't find the class by that name. I also notice that
nested classes don't seem to be mentioned in the refection API
(i.e they don't qualify as members). So should I give up, or is there
a way to make such beasts using reflection.