Is there a way to create ruby value objects or hashes from java objects in jruby application ? Thank you.
2 Answers
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)
1 Comment
Fivell
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 .
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
Gary S. Weaver
That almost worked for me. I had to change the one conditional to: next if 'get_class' == accessor.try(:to_s)