JPython and Java Class Loader

shindich at my-deja.com shindich at my-deja.com
Wed Sep 27 12:24:18 EDT 2000


I am having the following problem with JPython:
JPython uses it's own class loader, as a result, JPython loads it's own
copy of each Java class that my scripts use. Each such class instance
has JPython's class loader attached to it. JVM thinks that two class
objects are the same if both the class types and the class loaders
match.
This means that if I use class Foo from java, and I use class Foo from
Python, they will have two different class objects attached to them.
As a result, I cannot affect static Java class members from within my
Python scripts.

Does anyone have any suggestions on how I can make JPython use JVM's
default class loader for regular Java classes?

The following is the source code that I'm trying to get to work:
B.java:
-----------------------------------------------------------------
import java.util.*;

public class B
{
// This doesn't work
private static Map map = new HashMap ();
public static int getValue () { return map.size (); }
public static void incValue () { map.put (new Integer (getValue ()),
new Integer (getValue ()));}
}
A.java:
-----------------------------------------------------------------
import org.python.util.PythonInterpreter;
import org.python.core.*;

public class A
{
  public static void main (String [] args)
  {
    PythonInterpreter interp = new PythonInterpreter();
    interp.exec ("import pymodule");
    System.out.print ("The current value is " + B.getValue ());

    # Print out the class and the class loader for Java class B
    B b = new B ();
    System.out.print ("\n" + b.getClass ().getName ());
    System.out.print ("\n" + b.getClass ().getClassLoader ());
  }
}
pymodule.py:
-----------------------------------------------------------------
import B
# Increment the value 10 times
for i in range (10):
	B.incValue ()

# Print out the class and the class loader for Java class B
b = B ()
print b.getClass ().getName ()
print b.getClass ().getClassLoader ()

-----------------------------------------------------------------

Just compile A.java and B.java and run "java A"
Here is what I get:
----------------------------------------
D:\temp\foo>java A
B
org.python.core.BytecodeLoader at dd229e1c
The current value is 0
B
sun.misc.Launcher$AppClassLoader at 7ad69e1c
----------------------------------------
I was hoping to see:
----------------------------------------
D:\temp\foo>java A
B
sun.misc.Launcher$AppClassLoader at 7ad69e1c
The current value is 10
B
sun.misc.Launcher$AppClassLoader at 7ad69e1c


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list