Source

pypy / pypy / rlib / rjvm.py

import jpype
import atexit


class CallWrapper(object):    
    
    def wrap_item(self, item):
        if isinstance(item, jpype.java.lang.Object):
            return JavaInstanceWrapper(item)
        elif isinstance(item, jpype._jclass._JavaClass):
            return JavaInstanceWrapper(item.__javaclass__)
        elif isinstance(item, tuple) or isinstance(item, list):
            return self.wrap_list(item)
        return item

    def wrap_list(self, lst):
        return [self.wrap_item(x) for x in lst]

    def __call__(self, *args, **kwargs):
        result =  self.__wrapped__(*args, **kwargs)
        return self.wrap_item(result)


class JavaWrapper(CallWrapper):
    def __init__(self, name):
        self.__javaname__ = name
        all_names = name.split(".")
        temp_module = jpype
        for n in all_names:
            temp_module = getattr(temp_module, n)
        self.__wrapped__ = temp_module
    def __getattr__(self, attr):
        if isinstance(getattr(self.__wrapped__, attr), type):
            return JavaClassWrapper(getattr(self.__wrapped__, attr))
        elif isinstance(getattr(self.__wrapped__, attr), jpype.JPackage):
            return JavaWrapper(self.__javaname__ + '.' + attr)

class JavaInstanceWrapper(object):
    def __init__(self, obj):
        self.__wrapped__ = obj

    def __getattr__(self, attr):
        return JavaMethodWrapper(getattr(self.__wrapped__, attr))

class JavaClassWrapper(CallWrapper):
    def __init__(self, cls):
        self.__wrapped__ = cls

    def __getattr__(self, attr):
        result = None
        try:
            result = JavaStaticMethodWrapper(getattr(self.__wrapped__, attr))
        except AttributeError:
            result = JavaStaticMethodWrapper(getattr(self.__wrapped__.__javaclass__, attr))
        return result

class JavaMethodWrapper(CallWrapper):

    def __init__(self, meth):
        self.__wrapped__ = meth

class JavaStaticMethodWrapper(CallWrapper):
    def __init__(self, static_meth):
        self.__wrapped__ = static_meth
    


jpype.startJVM(jpype.getDefaultJVMPath(), "-ea")
java = JavaWrapper("java")
JavaMethod = type(jpype.java.lang.Math.abs)


def cleanup():
    jpype.shutdownJVM()

atexit.register(cleanup)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.