Jython: Determine the number of arguments a Java method takes at runtime

假如想象 提交于 2019-12-13 05:45:06

问题


I'm trying to write an object inspector for Java objects in Jython, and I want to determine how many arguments a given Java method expects. Is there any way to do that in python, or do I have to use Java reflection for that.

To explain, I'd like to call all "get..." methods of a Java object that don't take any arguments:

from java.util import Date, ArrayList

def numberOfArguments(fct):
  # Some magic happens here
  return 0

def check(o):
  print("")
  print(type(o).name)
  for fctName in dir(o):
    if not str(fctName).startswith("get"): continue
    print("== " + fctName)
    fct = eval("o."+fctName)
    if numberOfArguments(fct) == 0:
      print(" " + str(fct()))

check(Date())
check(ArrayList())

回答1:


Oh well, turns out I was doing the wrong thing by using dir(obj). It's just way easier to use o.getCalss().getMethods(). This way, I also don't get bitten by overloading methods.

from java.util import Date, ArrayList

def numberOfArguments(fct):
  # Not very magic:
  return len(fct.getParameterTypes())

def check(o):
  print("")
  print(type(o).name)
  # Use Java reflection instead of Python dir() function
  for fct in o.getClass().getMethods():
    fctName = fct.getName()
    if not str(fctName).startswith("get"): continue
    print("== " + fctName)
    if numberOfArguments(fct) == 0:
      print(" " + str(fct.invoke(o, [])))

check(Date())
check(ArrayList())


来源:https://stackoverflow.com/questions/16774298/jython-determine-the-number-of-arguments-a-java-method-takes-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!