From: Charles Oliver Nutter Date: 2010-04-25T16:41:07+09:00 Subject: Re: DrX, an object inspector On Sat, Apr 24, 2010 at 10:38 AM, David Masover wrote: >> For getting the data, you don't even need to write an extension to >> JRuby. The "jruby" library gives you introspective access to all >> objects at a very direct level: > It seems like this should be possible to do from bare Ruby, in a portable way. > Clumsy, but possible. For example, as long as people don't get smart and use > Ruby 1.9's BasicObject, you can do this: No, I'm pretty sure this isn't possible on regular Ruby. What's happening in JRuby is that you're getting direct access to the Java object representing a Ruby class or object, and you then can do anything to that object you'd normally have to write Java code for. Now that I'm on my machine, here's a more extensive example: require 'jruby' class MyObject def foo 'hello' end end obj = MyObject.new cls = obj.class obj_ref = JRuby.reference obj cls_ref = JRuby.reference cls # accessing the raw method table on a class methods = cls_ref.getMethods # this was the ".methods" call previously p methods.class # => Java::JavaUtilConcurrent::ConcurrentHashMap foo_method = methods['foo'] # foo_method is an instance of our internal method object p foo_method.call(JRuby.runtime.current_context, obj, cls_ref, 'foo') # => 'hello' # changing the object's class(!?) class Foo; end p obj.class # => 'Object' obj_ref.setMetaClass(JRuby.reference(Foo)) p obj.class # => 'Foo' # modifying the current scope scope = JRuby.runtime.current_context.current_scope p scope.static_scope.variables.to_a # => ["obj", "cls", "obj_ref", "cls_ref", "methods", "foo_method", "scope"] index = scope.static_scope.variables.to_a.index('scope') scope.set_value_depth_zero('hello', index) p scope # => 'hello' ...and so on. Essentially anything you can call from Java, you can call from Ruby once you have the appropriate reference, so you should be able to programmatically walk all of the JRuby runtime structures and any Ruby or Java objects they reference without writing any Java code. - Charlie