Method of invoking Java with variable parameters in JRuby

Source: Internet
Author: User

The problem that colleagues encounter today is to call a Java method with JRuby, which uses the jdk1.5 variable parameters. I thought it would be simple to represent a variable parameter as an array, such as the following two Java classes:

public class Echo{
  public void echo(String name){
    System.out.println(name);
  }
}
public class Test{
  public void hello(String name,Echoargs){
    System.out.println("hello,"+name);
    for(Echo e:args){
      e.echo(name);
    }
  }
}

I want to call the Hello method of test in JRuby, which has a variable parameter args. The so-called variable parameters are compiled in fact the array, which can be observed by the byte code, so if the array to call can not?

Require ' Java '

Require ' Test.jar '

Include_class ' Test '

Include_class ' Echo '

T.hello ("Dennis") #报错, parameters do not match

T.hello ("Dennis", []) #报错, type mismatch Unfortunately, this call is wrong, for reasons such as the above comment. Specific to type mismatch, the intrinsic reason is that the array in JRuby is inconsistent with the byte-code representation of the arrays in Java, the array in JRuby is represented by the Org.jruby.RubyArray class, and the array of the Hello method requires is [Lecho. The solution is to convert the JRuby array to the Java-required type, through the To_java method, so the following call is correct, despite the obvious trouble:

require 'java'
require 'test.jar'
include_class 'Test'
include_class 'Echo'
t=Test.new
t.hello("dennis",[].to_java("Echo"))
e1=Echo.new
t.hello("dennis",[e1].to_java("Echo"))
e2=Echo.new
t.hello("dennis",[e1,e2].to_java("Echo"))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.