开发者

Java method introspection from JRuby

开发者 https://www.devze.com 2023-01-02 02:37 出处:网络
Is there a way from JRuby to introspect on a Java object and find out its Java-land methods? Like what http://github.com/oggy/looksee provides, but for Java. Or like

Is there a way from JRuby to introspect on a Java object and find out its Java-land methods? Like what http://github.com/oggy/looksee provides, but for Java. Or like

(someobject).methods - 开发者_开发问答1.methods

This would be nice for just taking a look at what a Java object provides versus the APIDoc for it.


Looksee patches the interpreter, which is the reason why it only works on MRI and YARV and not on JRuby, XRuby, IronRuby, Ruby.NET, Rubinius, tinyrb, RubyGoLightly, MacRuby, HotRuby, BlueRuby, Cardinal, MagLev, SmallRuby, Red Sun and all the other implementations.

So, if you are willing to patch HotSpot, I'm sure you can whip up a Java-equivalent :-)

As for your basic introspection, it just works™:

require 'java'
java.lang.String.public_instance_methods.sort.reject {|m| m =~ /[_?!=~<>]/ }
# => [:bytes, :charAt, :class, :clone, :codePointAt, :codePointBefore, 
# => :codePointCount, :com, :compareTo, :compareToIgnoreCase, :concat, 
# => :contains, :contentEquals, :display, :dup, :empty, :endsWith, :equals, 
# => :equalsIgnoreCase, :extend, :finalize, :freeze, :getBytes, :getChars, 
# => :getClass, :hash, :hashCode, :id, :indexOf, :initialize, :inspect, :intern, 
# => :isEmpty, :java, :javax, :lastIndexOf, :length, :matches, :method, 
# => :methods, :notify, :notifyAll, :offsetByCodePoints, :org, :regionMatches, 
# => :replace, :replaceAll, :replaceFirst, :send, :split, :startsWith, 
# => :subSequence, :substring, :synchronized, :taint, :tap, :toCharArray, 
# => :toLowerCase, :toString, :toUpperCase, :trim, :trust, :type, :untaint, 
# => :untrust, :wait]

Of course, one of the main points of JRuby is to integrate the Java and Ruby object models as closely as possible, so we are actually getting both Java and Ruby methods here, but by rejecting all methods with characters that are unusual or plain illegal in Java, we get a reasonably clean list and the remaining Ruby methods are not that hard to spot.


Use the underlying Java class and normal reflection to get only the Java methods:

java.lang.String.java_class.declared_instance_methods

This maps directly to the Class.getDeclaredMethods() Java method call, and yields an array of Java::JavaMethod objects for each Java instance method on the target class.

0

精彩评论

暂无评论...
验证码 换一张
取 消