Jython: Determine the number of arguments a Java m

2019-09-15 11:11发布

问题:

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())