JPython embed question

Alex Martelli aleaxit at yahoo.com
Fri Dec 22 12:03:49 CET 2000


"Randy Heiland" <heiland at ncsa.uiuc.edu> wrote in message
news:3A42AA88.D9BD321A at ncsa.uiuc.edu...
> In the JPython demo/embed example, we find how to create an instance of
> a class, e.g.:
>
>   interp.set("foo1", new Foo());
>   interp.set("bar1", new Bar());
>
> I'd like to be able to dynamically create an instance of a class - e.g.,
>
>   createInstance(String instName, String className)

Java's "reflection" abilities is what you use for this -- most
of them are in package java.lang.reflect, although the crucial
java.lang.Class class is in java.lang for historical reasons.

Static method forName(String className) of class java.lang.Class:
"Given the fully-qualified name for a class, this method attempts
to locate, load, and link the specified class. If it succeeds,
returns the Class object representing the class".

Once you do have the java.lang.Class object, representing the
class whose fully-qualified name you started with, you call
its newInstance() method, and get an Object "just as if" you
has executed a 'new Foo()' expression.

All of this is really core Java stuff, with marginal specific
relevance to JPython.  I'd recommend the Java tutorial,
specifically http://java.sun.com/docs/books/tutorial/reflect/
for reflection issues.


Alex









More information about the Python-list mailing list