2

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

1

2 Answers 2

3

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)

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

1 Comment

thanks declared_fields works fine but I need totally ruby native hash, but in this way values can be such for example "createDatetime"=>#<Java::JavaUtil::Date:0x34a205d1>, I need to get all properties that have accessors to hash wich should have only ruby type values .
2

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

1 Comment

That almost worked for me. I had to change the one conditional to: next if 'get_class' == accessor.try(:to_s)

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.