Skip to content

Instantly share code, notes, and snippets.

@pmahoney
Last active March 15, 2023 00:45
Show Gist options
  • Save pmahoney/4686262 to your computer and use it in GitHub Desktop.
Save pmahoney/4686262 to your computer and use it in GitHub Desktop.
Test of become_java! and having java code call a ruby object.
require 'jruby/core_ext'
class MyObserver
include Java::JavaUtil::Observer
def update(observable, arg)
puts "UPDATE! #{observable}"
end
end
MyObserver.become_java! false
name = MyObserver.java_class.to_s
### Pretend a third-party Java module is doing the following:
puts "loading #{name}"
klass = Java::JavaLang::Thread.currentThread.getContextClassLoader.loadClass name
inst = klass.newInstance
puts "have instance: #{inst}"
inst.update('(invoked from JRuby)', nil)
observable = Java::JavaUtil::Observable.new
observable.addObserver(inst)
observable.setChanged
observable.notifyObservers
jruby -v test.rb
jruby 1.7.2 (1.9.3p327) 2013-01-04 302c706 on Java HotSpot(TM) 64-Bit Server VM 1.6.0_35-b10-428-10M3811 [darwin-x86_64]
loading rubyobj.MyObserver
have instance: #<MyObserver:0x1a0283e>
UPDATE! (invoked from JRuby)
Observable.java:142:in `notifyObservers': java.lang.AbstractMethodError: rubyobj.MyObserver.update(Ljava/util/Observable;Ljava/lang/Object;)V
from Observable.java:98:in `notifyObservers'
from NativeMethodAccessorImpl.java:-2:in `invoke0'
from NativeMethodAccessorImpl.java:39:in `invoke'
from DelegatingMethodAccessorImpl.java:25:in `invoke'
from Method.java:597:in `invoke'
from JavaMethod.java:440:in `invokeDirectWithExceptionHandling'
from JavaMethod.java:304:in `invokeDirect'
from InstanceMethodInvoker.java:52:in `call'
from CachingCallSite.java:306:in `cacheAndCall'
from CachingCallSite.java:136:in `call'
from test.rb:23:in `__file__'
from test.rb:-1:in `load'
from Ruby.java:810:in `runScript'
from Ruby.java:803:in `runScript'
from Ruby.java:674:in `runNormally'
from Ruby.java:523:in `runFromMain'
from Main.java:390:in `doRunFromMain'
from Main.java:279:in `internalRun'
from Main.java:221:in `run'
from Main.java:201:in `main'
@mikedll
Copy link

mikedll commented Mar 15, 2023

Thank you for sharing this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment