_jproxy.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #*****************************************************************************
  2. # Copyright 2004-2008 Steve Menard
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. #*****************************************************************************
  17. import collections
  18. import sys
  19. import _jpype
  20. from . import _jclass
  21. from . import JClassUtil
  22. if sys.version > '3':
  23. unicode = str
  24. def _initialize():
  25. _jpype.setProxyClass(JProxy)
  26. class JProxy(object):
  27. def __init__(self, intf, dict=None, inst=None):
  28. actualIntf = None
  29. if isinstance(intf, str) or isinstance(intf, unicode):
  30. actualIntf = [_jclass.JClass(intf)]
  31. elif isinstance(intf, _jclass._JavaClass):
  32. actualIntf = [intf]
  33. elif isinstance(intf, collections.Sequence):
  34. actualIntf = []
  35. for i in intf:
  36. if isinstance(i, str) or isinstance(i, unicode):
  37. actualIntf.append(_jclass.JClass(i))
  38. elif isinstance(i, _jclass._JavaClass):
  39. actualIntf.append(i)
  40. else:
  41. raise TypeError("JProxy requires java interface classes "
  42. "or the names of java interfaces classes")
  43. else:
  44. raise TypeError("JProxy requires java interface classes "
  45. "or the names of java interfaces classes")
  46. for i in actualIntf:
  47. if not JClassUtil.isInterface(i):
  48. raise TypeError("JProxy requires java interface classes "
  49. "or the names of java interfaces classes: {0}"
  50. .format(i.__name__))
  51. if dict is not None and inst is not None:
  52. raise RuntimeError("Specify only one of dict and inst")
  53. self._dict = dict
  54. self._inst = inst
  55. self._proxy = _jpype.createProxy(self, actualIntf)
  56. def getCallable(self, name):
  57. if self._dict is not None:
  58. return self._dict[name]
  59. else:
  60. return getattr(self._inst, name)