Skip to content

Instantly share code, notes, and snippets.

@hungtatai
Last active December 14, 2015 04:59
Show Gist options
  • Save hungtatai/5031837 to your computer and use it in GitHub Desktop.
Save hungtatai/5031837 to your computer and use it in GitHub Desktop.

jruby中java的implements interface

on jruby-1.6.8


implement interface的作法

如果在jruby想操作java的interface,如Runnable

直接include但不override需要的method,在還沒有執行前都是不會出現錯誤的

jruby-1.6.8 :075 > class MyRunnable
jruby-1.6.8 :076?>   include java.lang.Runnable
jruby-1.6.8 :077?> end
 => MyRunnable 
jruby-1.6.8 :078 > t = java.lang.Thread.new MyRunnable.new
 => #<Java::JavaLang::Thread:0x7a0aae8a> 

但是到執行的時候,因為沒有override method,就會出現沒有method的錯誤

jruby-1.6.8 :079 > t.start
Exception in thread "Thread-9"  => nil 
org.jruby.exceptions.RaiseException: (NoMethodError) undefined method `run' for #<MyRunnable:0x470794d4>

只要加入必要的method就好

jruby-1.6.8 :087 > class MyRunnable
jruby-1.6.8 :088?>   include java.lang.Runnable
jruby-1.6.8 :089?>   
jruby-1.6.8 :090 >     def run
jruby-1.6.8 :091?>        puts 'on run'
jruby-1.6.8 :092?>     end
jruby-1.6.8 :093?>   end
 => nil 
jruby-1.6.8 :094 > t = java.lang.Thread.new MyRunnable.new
 => #<Java::JavaLang::Thread:0x461d318f> 
jruby-1.6.8 :095 > t.start
on run
 => nil 

另外也有類似java裡anonymous inner class的用法。

在所有java的interface,都有impl這個method,且只有interface有,class沒有。

在interface沒有找到必要的method時,就會呼叫impl,有點像是missing_method。

jruby-1.6.8 :096 > r = java.lang.Runnable.impl do |method, evt|
jruby-1.6.8 :097 >     puts 'method: '+method.to_s
jruby-1.6.8 :098?>     puts 'evt: '+evt.to_s
jruby-1.6.8 :099?>   end
 => #<#<Class:0x5ad3c69c>:0x519549e> 
jruby-1.6.8 :100 > t = java.lang.Thread.new r
 => #<Java::JavaLang::Thread:0x35a271f5> 
jruby-1.6.8 :101 > t.start
 => nil 
method: run
evt: 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment