Reflection & Nested Classes

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.
 
C

Chris Smith

Ian said:
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.

This is one of those ugly cases where implementation detail shines
through. Try "java.awt.geom.Rectangle2D$Float".

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
T

Tony Morris

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.

You can access nested classes using:
java.lang.Class#getClasses
java.lang.Class#getDeclaredClasses

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top