Andrei Beliankou
Andrei Beliankou

Reputation: 684

What does the 'require "java"' statement do in JRuby scripts?

I read about Java interoperability in Ruby, so using JRuby is an obvious choice. But somehow I don't really grasp the idea behind require 'java'. The documentation says:

... will give you access to any bundled Java libraries (classes within your java class path). However, this will not give you access to any non-bundled libraries.

Are there any more elaborated explanations?

To be more precise I don't understand why the following code works without require "java":

$ export CLASSPATH=".:lib/opennlp-tools-1.6.0.jar" $ jruby -e 't = Java::OpennlpToolsTokenize::SimpleTokenizer.new; puts t.tokenize("I went to school").to_a'

Upvotes: 1

Views: 1351

Answers (1)

Thomas Enebo
Thomas Enebo

Reputation: 832

There are two parts to this question which need answering and some clarification we should make to our documentation (I made an attempt already in https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby):

  1. require 'java'. It loads the ability to load java classes and treat them as if they were Ruby objects/classes. However, Since JRuby 1.7.x, JRuby internally needs to require 'java' so it has already required 'java' by the time your expression is evaluated. So technically it is true that "require 'java'" loads Java interoperability, but since our kernel does this now it is largely a no-op by the time you call it (see return value of the require). We still recommend putting it at the top of any file where you use Java interop. just so it is documented in your code. Also, the fact that it happens to be loaded is more of an impl detail and not a semantic detail (e.g. in the distant future we maybe won't require it in our kernel).

  2. Unclear verbiage: "However, this will not give you access to any non-bundled libraries.". So if you want to access a library not in your CLASSPATH (this was stipulated in the parenthesis) you need to add them to your LOAD_PATH (or via direct require'ing). I tweaked that sentence to hopefully make it more clear.

Upvotes: 3

Related Questions