hello_its_me
hello_its_me

Reputation: 793

Importing .jar file in Ruby: how to use the class

The following is my jruby file called test.rb

require 'java'
require 'jruby.jar'

java_import 'jruby.Jruby'

puts "This is coming from Ruby."

And this is my Java code:

package jruby;
import javax.swing.JOptionPane;
public class Jruby {
    public static void main(String[] args) {
        String s = "This is coming from Java!";
        JOptionPane.showMessageDialog(null, s);
    }   
}

When I run jruby using the command

jruby test.rb

the only result I get is

this is coming from Ruby.

How can I initiate from the Java class to get the code in the Jar file executed? When I try to add the following:

var = new Jruby()

it gives me an error:

NoMethodError: undefined method `Jruby' for main:Object

Edit

Tried this, also didn't work. Package name is foo, class name is Foo

    require 'java'
    require 'foo.jar'

    java_import 'foo.Foo'
    puts "This is coming from Ruby."
    foo.Foo.main()

This gave the following error:

NameError: undefined local variable or method 'foo' for main:Object (root) at test.rb

FINAL FILE THAT WORKED WITH Meier'S HELP

require 'java'
require 'foo.jar'

java_import 'javax.swing.JOptionPane'
puts "This is coming from Ruby."

import 'foo.Foo'
Java::foo::Foo.hello()

hello() being the class that contains the Java code.

Upvotes: 3

Views: 5257

Answers (1)

Meier
Meier

Reputation: 3880

In jruby, you can access java classes by package name and class name. See https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

Your java main method is static, so no need for new. So this should work.

jruby.Jruby.main()

But I suggest to rename your java class and package. You may get name clashes, as it is likely that something inside jruby is also called jruby. Also the name is just wrong, because it is a java class and not a jruby class.

Edit:

After consulting the document, the above is only correct for standard java packages. There are several ways to access a java class:

  1. use Ruby Module Syntax:

    Java::Foo::Foo.main()

  2. the dot syntax, as I tried first.

"Second way: for the top-level Java packages java, javax, javafx, org, and com you can type in a fully qualified class name basically as in Java, for example, java.lang.System or org.abc.def.className ..."

You either need to put your java class in the package com.foo or write an extra method to access the package:

def edu
  Java::Edu
end

"And then you can use use usual Java package names like edu.abc.def.ClassName"

  1. after java_import, the imported Class "will be available in the global name space"

    java_import 'foo.Foo'

    Foo.main()

In all cases, you need to make sure that jruby sees the your jar file.

" loading jar-files via require searches along the $LOAD_PATH for them, like it would for normal ruby files."

Upvotes: 4

Related Questions