Help us understand the problem. What is going on with this article?

JRubyからJavaを呼び出す

More than 1 year has passed since last update.

経緯

やり方

(前提)JRubyを使える・javaをコンパイルできる
1. Javaのコードを書く(ファイル名をJavaCallTest.javaとします)
2. JavaCallTest.javaをコンパイルしてJavaCallTest.classを用意
3. JRuby内でrequire 'java'; java_import 'JavaCallTest'
4. 適当に呼び出す

以下、具体例。

Javaのコード

JavaCallTest.java
public class JavaCallTest{
    public static String str1(){
        return "str1";
    }

    public String str2() {
        return "str2";
    }
}

JRubyのコード

java_call_test.rb
require 'java'
java_import 'JavaCallTest'

p JavaCallTest.str1
begin
  jct1 = JavaCallTest.new
  jct1.str1
rescue => e
  puts e.class
  puts e.message
  puts e.backtrace
end

jct2 = JavaCallTest.new
p jct2.str2
begin
  p JavaCallTest.str2
rescue => e
  puts e.class
  puts e.message
  puts e.backtrace
end

結果

$ jruby CallJava1.rb 
"str1"
NoMethodError
undefined method `str1' for #<Java::Default::JavaCallTest:0x553a3d88>
Did you mean?  str2
CallJava1.rb:7:in `<main>'
"str2"
NoMethodError
undefined method `str2' for Java::Default::JavaCallTest:Class
Did you mean?  str1
org/jruby/RubyBasicObject.java:1657:in `method_missing'
CallJava1.rb:17:in `<main>'

コメント

呼び方が以下のように対応するらしい

  • JavaのstaticソッドがRubyのクラスメソッド
  • Javaの非staticソッドがRubyのインスタンスメソッド

Javaの知識が0だったので大変でした

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away