Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I import Java class files into JRuby?

The documentation seems to suggest that in order for me to import Java classes into JRuby, that they must be in a JAR file:

"In order to use resources within a jar file from JRuby the jar file must either be on the classpath or you can make it available with the require method" (http://wiki.jruby.org/wiki/Calling_Java_from_JRuby#Require_a_jar_file_to_make_resources_in_the_jar_discoverable_within_JRuby)

Is it at all possible to import .class files directly?

Thanks!

like image 729
bjnortier Avatar asked Jan 09 '09 17:01

bjnortier


People also ask

How do I import a Java class file?

To import java package into a class, we need to use java import keyword which is used to access package and its classes into the java program. Use import to access built-in and user-defined packages into your java source file so that your class can refer to a class that is in another package by directly using its name.

Can classes be imported in Java?

You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.

Can we import class from same package in Java?

In Java, you do not need to add import statements for classes that exist within the same package (they are actually automatically “imported” by the compiler).


2 Answers

I've managed to answer my own question :)

If your class files are compiled to a relative path of "target", e.g. foo.Bar is located in "target/foo/Bar.class", then you do the following:

require 'java'
require 'target/foo/Bar'

module Foo
  include_package 'foo'
end

puts Foo::Bar.new

And the result:

foo.Bar@1582a7c
like image 197
bjnortier Avatar answered Oct 03 '22 13:10

bjnortier


I think you could also:

require 'java'
$CLASSPATH << "target"

and then

foo.bar.baz.Class.new() # ... 
# or 
java_import 'foo.bar.baz.Class'
like image 36
reto Avatar answered Oct 01 '22 13:10

reto