简体   繁体   中英

Passing JRuby objects to Java methods?

How can I pass a JRuby object (it's a quite simple object, containing a few fields of string and Hash type) to a method defined in a Java class?

UPD here is a serialized content of a type I need to share between JRuby and Java code:

--- !ruby/object:LogStash::Event cancelled: false data: &1 message: "q\\r" '@version': '1' '@timestamp': 2015-02-17 12:10:17.695000000 Z type: human accessors: !ruby/object:LogStash::Util::Accessors store: *1 lut: type: - *1 - type host: - *1 - host The object is created by JRuby side. Ideally, I could access this object directly from Java and modify it. Less ideally, I need to convert it to something understandable by Java and then back.

simply specify an Object or IRubyObject argument signature in the method and it will work just fine when you call the Java method from your Ruby script ...

UPDATE : assuming a LogStash::Event you can either make the Java signature accept (IRubyObject event) and than use event.callMethod("cancelled?").isTrue() and similar on the Java side OR :

... if you mostly only need its @data on the Java side the internal Ruby Hash can be easily retrieved using: event.to_hash pass this to a Java signature accepting (Map<String, ?> eventData) you can easily retrieve eventData.get("message") and even update the data eventData.put("message", 42) it will be reflected on the Ruby side without additional work since Ruby hashes implement the Map interface and thus will be passed around without conversion (it will internally handle simple Ruby to Java string conversion and similar auto-magically)

otherwise (for sanity) I would recommend to introduce a simple bridge object that would wrap the event be passed into Java and handle the use-cases you need to invoke on the Java side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM