Fivell
Fivell

Reputation: 11929

Bind Java objects to ruby hashes

Is there a way to create ruby value objects or hashes from java objects in jruby application ? Thank you.

Upvotes: 2

Views: 1297

Answers (2)

Fivell
Fivell

Reputation: 11929

Names and Beans Convention gives us next opportunity for properties with accessors

def java_to_hash(java_obj)
    hash = {}
    java_obj.methods.grep(/get_/).each do |accessor|

      if accessor.eql? "get_class" then
        next
      end

      #get_user_name => user_name
      method_name = accessor[4..-1]

      if java_obj.respond_to?(method_name)
        hash[method_name.to_sym] = java_obj.send(accessor.to_sym)
      end
    end
    hash
end

Upvotes: 2

I am not sure whether this is what you are trying to achieve, but to convert a Java object into a ruby hash, you could do something like this:

require 'java'
java_import 'YourJavaClass'

a = YourJavaClass.new
hash = {}
a.java_class.fields.each{ |var| hash[var.name] = var.value(a) }
p hash

This assumes that the instance variables are accessible (public). If they are not, you may need to make them accessible with something like:

a.java_class.declared_fields.each{ |var| var.accessible = true; hash[var.name] = var.value(a) }

(Note that this time it uses declared_fields)

Upvotes: 3

Related Questions