Skip to content

Commit 0a8141c

Browse files
committed
Add some functions for Java object introspection
1 parent 1e54c4b commit 0a8141c

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/scyjava/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@
124124
jclass,
125125
jinstance,
126126
jstacktrace,
127+
methods,
127128
numeric_bounds,
128129
)
129130
from ._versions import compare_version, get_version, is_version_at_least

src/scyjava/_types.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,55 @@ def numeric_bounds(
324324
return None, None
325325

326326

327+
def methods(data) -> list[dict[str, Any]]:
328+
"""
329+
Use Java reflection to introspect the given Java object,
330+
returning a table of its available methods.
331+
332+
:param data: The object or class to inspect.
333+
:return: List of table rows with columns "name", "arguments", and "returns".
334+
"""
335+
336+
if not isjava(data):
337+
raise ValueError("Not a Java object")
338+
339+
cls = data if jinstance(data, "java.lang.Class") else jclass(data)
340+
341+
methods = cls.getMethods()
342+
343+
# NB: Methods are returned in inconsistent order.
344+
# Arrays.sort(methods, (m1, m2) -> {
345+
# final int nameComp = m1.getName().compareTo(m2.getName())
346+
# if (nameComp != 0) return nameComp
347+
# final int pCount1 = m1.getParameterCount()
348+
# final int pCount2 = m2.getParameterCount()
349+
# if (pCount1 != pCount2) return pCount1 - pCount2
350+
# final Class<?>[] pTypes1 = m1.getParameterTypes()
351+
# final Class<?>[] pTypes2 = m2.getParameterTypes()
352+
# for (int i = 0; i < pTypes1.length; i++) {
353+
# final int typeComp = ClassUtils.compare(pTypes1[i], pTypes2[i])
354+
# if (typeComp != 0) return typeComp
355+
# }
356+
# return ClassUtils.compare(m1.getReturnType(), m2.getReturnType())
357+
# })
358+
359+
table = []
360+
361+
for m in methods:
362+
name = m.getName()
363+
args = [c.getName() for c in m.getParameterTypes()]
364+
returns = m.getReturnType().getName()
365+
table.append(
366+
{
367+
"name": name,
368+
"arguments": args,
369+
"returns": returns,
370+
}
371+
)
372+
373+
return table
374+
375+
327376
def _is_jtype(the_type: type, class_name: str) -> bool:
328377
"""
329378
Test if the given type object is *exactly* the specified Java type.

0 commit comments

Comments
 (0)