3

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.