Eclipse JNI with .java file in package - java

I am writing a simple demo JNI project in Eclipse to integrate Java and C code. I have installed the CDT plugin for Eclipse to do this.
With this project structure I have my HelloJNI java file inside the '(default package)' of Eclipse and have no problems using the makefile to generate a HelloJNI.h C header file.
My Makefile:
# Define a variable for classpath
CLASS_PATH = ../bin
# Define a virtual path for .class in the bin directory
vpath %.class $(CLASS_PATH)
# $* matches the target filename without the extension
HelloJNI.h : HelloJNI.class
javah -classpath $(CLASS_PATH) HelloJNI
The problem is that I cannot figure out how to get this to work with HelloJNI.java being inside a package such as com.example instead of the default package. i.e. this structure. When running the same make target I get the error output:
make: *** No rule to make target 'HelloJNI.class', needed by 'HelloJNI.h'. Stop.
I attempted to add the package name to the javah command:
javah -classpath $(CLASS_PATH) com.example.HelloJNI
...but get the same error.
I attempted to change the classpath to:
CLASS_PATH = ../bin/com/example
...but get the following error:
make HelloJNI.h
javah -classpath ../bin/com/example HelloJNI
Error: Could not find class file for 'HelloJNI'.
What do I need to do with my makefile to make this work?

The javah utility expects you to give it the fully-qualified name of the class you want it to analyze, and it expects to find that class relative to the classpath, according to that name. Thus, if the name of the class is com.example.HelloJNI, then you might tell make something like this:
CLASS_DIR = ../bin
HelloJNI.h : $(CLASS_DIR)/com/example/HelloJNI.class
javah -force -classpath $(CLASS_DIR) com.example.HelloJNI
You can dress that up a bit if you want. I use something a little DRYer and with a bit more automation in my own Makefiles, but I'm trying to get across the key points. In particular:
Express the correct prerequisite file (the .class file, in the correct directory). If you do not do this correctly then you will end up having your header sometimes being rebuilt when it does not need to be and / or not being updated when it does need to be.
Specify an appropriate -classpath to javah; this follows the normal Java rules for expressing class paths.
Specify the correct, fully-qualified class name to javah.
Use the -force option, else javah will refuse to replace headers that already exist. That default behavior is reasonable when you invoke javah manually, but it will mess you up when you are trying to use make to keep the JNI headers up to date. Of course, it follows that you must not make manual modifications to those headers, because such modifications are likely to be clobbered.

Related

Compiling packages in java at windows command line

I have trying to compile java files at the windows command line using commands such as:
java myProg once I have used javac to create class files.
Problems arise when I use packages with a number of source files.
Often but not always I get main not found errors even though a main exists.
I am not quite sure what some of the directives mean and that is why it seems hit or miss.
Question
what does -cp mean exactly? java -cp src\myDirectory.myfile
sometimes I see:
./ infront of source eg .\src\myDirectory.myfile
on other sites I have found
% javac -cp .;stdlib.jar MyProgram.java
% java -cp .;stdlib.jar MyProgram
while compiling a jar library with java source files
what doesthe ".;" mean?
basically how do I compile three java source java files in one package at the windows command line and what does -cp and .; mean?
-cp means class path if I'm not mistaken.
try reading the following java docs
-classpath path
Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by semi-colons. It is often useful for the directory containing the source files to be on the class path. You should always include the system classes at the end of the path. For example:
javac -classpath .;C:\users\dac\classes;C:\tools\java\classes ...
https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/win32/javac.html
Answering your question directly, -cp means classpath or path.
Details on commandline arguments used while compiling and running a Java application can be found here: javac - Java programming language compiler
Extracting the description of -cp from that page:
-cp path or -classpath path:
Specify where to find user class files, and (optionally) annotation processors and source files. This class path overrides the user class path in the CLASSPATH environment variable. If neither CLASSPATH, -cp nor -classpath is specified, the user class path consists of the current directory. See Setting the Class Path for more details.
. means the current directory.
To compile multiple files in a directory use the following:
javac *.java // compliles all java files in the dir
java MyClass // runs the particular file
There are also a bunch of other related questions that should help you resolve this:
How to run a java program from the command line
How do I run java program with multiple classes from cmd?
Problems running a java program from the command line interface
Can't run multiple-class program from command line using packages

What are the common errors you see when you run 'java -cp ...' or 'java -classpath'? How do you set a directory of jars in classpath? [duplicate]

Is there a way to include all the jar files within a directory in the classpath?
I'm trying java -classpath lib/*.jar:. my.package.Program and it is not able to find class files that are certainly in those jars. Do I need to add each jar file to the classpath separately?
Using Java 6 or later, the classpath option supports wildcards. Note the following:
Use straight quotes (")
Use *, not *.jar
Windows
java -cp "Test.jar;lib/*" my.package.MainClass
Unix
java -cp "Test.jar:lib/*" my.package.MainClass
This is similar to Windows, but uses : instead of ;. If you cannot use wildcards, bash allows the following syntax (where lib is the directory containing all the Java archive files):
java -cp "$(printf %s: lib/*.jar)"
(Note that using a classpath is incompatible with the -jar option. See also: Execute jar file with multiple classpath libraries from command prompt)
Understanding Wildcards
From the Classpath document:
Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files
in the directory with the extension .jar or .JAR. For example, the
class path entry foo/* specifies all JAR files in the directory named
foo. A classpath entry consisting simply of * expands to a list of all
the jar files in the current directory.
A class path entry that contains * will not match class files. To
match both classes and JAR files in a single directory foo, use either
foo;foo/* or foo/*;foo. The order chosen determines whether the
classes and resources in foo are loaded before JAR files in foo, or
vice versa.
Subdirectories are not searched recursively. For example, foo/* looks
for JAR files only in foo, not in foo/bar, foo/baz, etc.
The order in which the JAR files in a directory are enumerated in the
expanded class path is not specified and may vary from platform to
platform and even from moment to moment on the same machine. A
well-constructed application should not depend upon any particular
order. If a specific order is required then the JAR files can be
enumerated explicitly in the class path.
Expansion of wildcards is done early, prior to the invocation of a
program's main method, rather than late, during the class-loading
process itself. Each element of the input class path containing a
wildcard is replaced by the (possibly empty) sequence of elements
generated by enumerating the JAR files in the named directory. For
example, if the directory foo contains a.jar, b.jar, and c.jar, then
the class path foo/* is expanded into foo/a.jar;foo/b.jar;foo/c.jar,
and that string would be the value of the system property
java.class.path.
The CLASSPATH environment variable is not treated any differently from
the -classpath (or -cp) command-line option. That is, wildcards are
honored in all these cases. However, class path wildcards are not
honored in the Class-Path jar-manifest header.
Note: due to a known bug in java 8, the windows examples must use a backslash preceding entries with a trailing asterisk: https://bugs.openjdk.java.net/browse/JDK-8131329
Under Windows this works:
java -cp "Test.jar;lib/*" my.package.MainClass
and this does not work:
java -cp "Test.jar;lib/*.jar" my.package.MainClass
Notice the *.jar, so the * wildcard should be used alone.
On Linux, the following works:
java -cp "Test.jar:lib/*" my.package.MainClass
The separators are colons instead of semicolons.
We get around this problem by deploying a main jar file myapp.jar which contains a manifest (Manifest.mf) file specifying a classpath with the other required jars, which are then deployed alongside it. In this case, you only need to declare java -jar myapp.jar when running the code.
So if you deploy the main jar into some directory, and then put the dependent jars into a lib folder beneath that, the manifest looks like:
Manifest-Version: 1.0
Implementation-Title: myapp
Implementation-Version: 1.0.1
Class-Path: lib/dep1.jar lib/dep2.jar
NB: this is platform-independent - we can use the same jars to launch on a UNIX server or on a Windows PC.
My solution on Ubuntu 10.04 using java-sun 1.6.0_24 having all jars in "lib" directory:
java -cp .:lib/* my.main.Class
If this fails, the following command should work (prints out all *.jars in lib directory to the classpath param)
java -cp $(for i in lib/*.jar ; do echo -n $i: ; done). my.main.Class
Short answer: java -classpath lib/*:. my.package.Program
Oracle provides documentation on using wildcards in classpaths here for Java 6 and here for Java 7, under the section heading Understanding class path wildcards. (As I write this, the two pages contain the same information.) Here's a summary of the highlights:
In general, to include all of the JARs in a given directory, you can use the wildcard * (not *.jar).
The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.
The above two options can be combined to include all JAR and class files in a directory, and the usual classpath precedence rules apply. E.g. -cp /classes;/jars/*
The wildcard will not search for JARs in subdirectories.
The above bullet points are true if you use the CLASSPATH system property or the -cp or -classpath command line flags. However, if you use the Class-Path JAR manifest header (as you might do with an ant build file), wildcards will not be honored.
Yes, my first link is the same one provided in the top-scoring answer (which I have no hope of overtaking), but that answer doesn't provide much explanation beyond the link. Since that sort of behavior is discouraged on Stack Overflow these days, I thought I'd expand on it.
Windows:
java -cp file.jar;dir/* my.app.ClassName
Linux:
java -cp file.jar:dir/* my.app.ClassName
Remind:
- Windows path separator is ;
- Linux path separator is :
- In Windows if cp argument does not contains white space, the "quotes" is optional
For me this works in windows .
java -cp "/lib/*;" sample
For linux
java -cp "/lib/*:" sample
I am using Java 6
You can try java -Djava.ext.dirs=jarDirectory
http://docs.oracle.com/javase/6/docs/technotes/guides/extensions/spec.html
Directory for external jars when running java
Correct:
java -classpath "lib/*:." my.package.Program
Incorrect:
java -classpath "lib/a*.jar:." my.package.Program
java -classpath "lib/a*:." my.package.Program
java -classpath "lib/*.jar:." my.package.Program
java -classpath lib/*:. my.package.Program
If you are using Java 6, then you can use wildcards in the classpath.
Now it is possible to use wildcards in classpath definition:
javac -cp libs/* -verbose -encoding UTF-8 src/mypackage/*.java -d build/classes
Ref: http://www.rekk.de/bloggy/2008/add-all-jars-in-a-directory-to-classpath-with-java-se-6-using-wildcards/
If you really need to specify all the .jar files dynamically you could use shell scripts, or Apache Ant. There's a commons project called Commons Launcher which basically lets you specify your startup script as an ant build file (if you see what I mean).
Then, you can specify something like:
<path id="base.class.path">
<pathelement path="${resources.dir}"/>
<fileset dir="${extensions.dir}" includes="*.jar" />
<fileset dir="${lib.dir}" includes="*.jar"/>
</path>
In your launch build file, which will launch your application with the correct classpath.
Please note that wildcard expansion is broken for Java 7 on Windows.
Check out this StackOverflow issue for more information.
The workaround is to put a semicolon right after the wildcard. java -cp "somewhere/*;"
To whom it may concern,
I found this strange behaviour on Windows under an MSYS/MinGW shell.
Works:
$ javac -cp '.;c:\Programs\COMSOL44\plugins\*' Reclaim.java
Doesn't work:
$ javac -cp 'c:\Programs\COMSOL44\plugins\*' Reclaim.java
javac: invalid flag: c:\Programs\COMSOL44\plugins\com.comsol.aco_1.0.0.jar
Usage: javac <options> <source files>
use -help for a list of possible options
I am quite sure that the wildcard is not expanded by the shell, because e.g.
$ echo './*'
./*
(Tried it with another program too, rather than the built-in echo, with the same result.)
I believe that it's javac which is trying to expand it, and it behaves differently whether there is a semicolon in the argument or not. First, it may be trying to expand all arguments that look like paths. And only then it would parse them, with -cp taking only the following token. (Note that com.comsol.aco_1.0.0.jar is the second JAR in that directory.) That's all a guess.
This is
$ javac -version
javac 1.7.0
All the above solutions work great if you develop and run the Java application outside any IDE like Eclipse or Netbeans.
If you are on Windows 7 and used Eclipse IDE for Development in Java, you might run into issues if using Command Prompt to run the class files built inside Eclipse.
E.g. Your source code in Eclipse is having the following package hierarchy:
edu.sjsu.myapp.Main.java
You have json.jar as an external dependency for the Main.java
When you try running Main.java from within Eclipse, it will run without any issues.
But when you try running this using Command Prompt after compiling Main.java in Eclipse, it will shoot some weird errors saying "ClassNotDef Error blah blah".
I assume you are in the working directory of your source code !!
Use the following syntax to run it from command prompt:
javac -cp ".;json.jar" Main.java
java -cp ".;json.jar" edu.sjsu.myapp.Main
[Don't miss the . above]
This is because you have placed the Main.java inside the package edu.sjsu.myapp and java.exe will look for the exact pattern.
Hope it helps !!
macOS, current folder
For Java 13 on macOS Mojaveā€¦
If all your .jar files are in the same folder, use cd to make that your current working directory. Verify with pwd.
For the -classpath you must first list the JAR file for your app. Using a colon character : as a delimiter, append an asterisk * to get all other JAR files within the same folder. Lastly, pass the full package name of the class with your main method.
For example, for an app in a JAR file named my_app.jar with a main method in a class named App in a package named com.example, alongside some needed jars in the same folder:
java -classpath my_app.jar:* com.example.App
For windows quotes are required and ; should be used as separator. e.g.:
java -cp "target\\*;target\\dependency\\*" my.package.Main
Short Form: If your main is within a jar, you'll probably need an additional '-jar pathTo/yourJar/YourJarsName.jar ' explicitly declared to get it working (even though 'YourJarsName.jar' was on the classpath)
(or, expressed to answer the original question that was asked 5 years ago: you don't need to redeclare each jar explicitly, but does seem, even with java6 you need to redeclare your own jar ...)
Long Form:
(I've made this explicit to the point that I hope even interlopers to java can make use of this)
Like many here I'm using eclipse to export jars: (File->Export-->'Runnable JAR File'). There are three options on 'Library handling' eclipse (Juno) offers:
opt1: "Extract required libraries into generated JAR"
opt2: "Package required libraries into generated JAR"
opt3: "Copy required libraries into a sub-folder next to the generated JAR"
Typically I'd use opt2 (and opt1 was definitely breaking), however native code in one of the jars I'm using I discovered breaks with the handy "jarinjar" trick that eclipse leverages when you choose that option. Even after realizing I needed opt3, and then finding this StackOverflow entry, it still took me some time to figure it out how to launch my main outside of eclipse, so here's what worked for me, as it's useful for others...
If you named your jar: "fooBarTheJarFile.jar"
and all is set to export to the dir: "/theFully/qualifiedPath/toYourChosenDir".
(meaning the 'Export destination' field will read: '/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar' )
After you hit finish, you'll find eclipse then puts all the libraries into a folder named 'fooBarTheJarFile_lib' within that export directory, giving you something like:
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar01.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar02.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar03.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar04.jar
You can then launch from anywhere on your system with:
java -classpath "/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*" -jar /theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain
(For Java Newbies: 'package.path_to.the_class_with.your_main' is the declared package-path that you'll find at the top of the 'TheClassWithYourMain.java' file that contains the 'main(String[] args){...}' that you wish to run from outside java)
The pitfall to notice: is that having 'fooBarTheJarFile.jar' within the list of jars on your declared classpath is not enough. You need to explicitly declare '-jar', and redeclare the location of that jar.
e.g. this breaks:
java -classpath "/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar;/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*" somepackages.inside.yourJar.leadingToTheMain.TheClassWithYourMain
restated with relative paths:
cd /theFully/qualifiedPath/toYourChosenDir/;
BREAKS: java -cp "fooBarTheJarFile_lib/*" package.path_to.the_class_with.your_main.TheClassWithYourMain
BREAKS: java -cp ".;fooBarTheJarFile_lib/*" package.path_to.the_class_with.your_main.TheClassWithYourMain
BREAKS: java -cp ".;fooBarTheJarFile_lib/*" -jar package.path_to.the_class_with.your_main.TheClassWithYourMain
WORKS: java -cp ".;fooBarTheJarFile_lib/*" -jar fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain
(using java version "1.6.0_27"; via OpenJDK 64-Bit Server VM on ubuntu 12.04)
You need to add them all separately. Alternatively, if you really need to just specify a directory, you can unjar everything into one dir and add that to your classpath. I don't recommend this approach however as you risk bizarre problems in classpath versioning and unmanagability.
The only way I know how is to do it individually, for example:
setenv CLASSPATH /User/username/newfolder/jarfile.jar:jarfile2.jar:jarfile3.jar:.
Hope that helps!
class from wepapp:
> mvn clean install
> java -cp "webapp/target/webapp-1.17.0-SNAPSHOT/WEB-INF/lib/tool-jar-1.17.0-SNAPSHOT.jar;webapp/target/webapp-1.17.0-SNAPSHOT/WEB-INF/lib/*" com.xx.xx.util.EncryptorUtils param1 param2
Think of a jar file as the root of a directory structure. Yes, you need to add them all separately.
Not a direct solution to being able to set /* to -cp but I hope you could use the following script to ease the situation a bit for dynamic class-paths and lib directories.
libDir2Scan4jars="../test";cp=""; for j in `ls ${libDir2Scan4jars}/*.jar`; do if [ "$j" != "" ]; then cp=$cp:$j; fi; done; echo $cp| cut -c2-${#cp} > .tmpCP.tmp; export tmpCLASSPATH=`cat .tmpCP.tmp`; if [ "$tmpCLASSPATH" != "" ]; then echo .; echo "classpath set, you can now use ~> java -cp \$tmpCLASSPATH"; echo .; else echo .; echo "Error please check libDir2Scan4jars path"; echo .; fi;
Scripted for Linux, could have a similar one for windows too. If proper directory is provided as input to the "libDir2Scan4jars"; the script will scan all the jars and create a classpath string and export it to a env variable "tmpCLASSPATH".
Set the classpath in a way suitable multiple jars and current directory's class files.
CLASSPATH=${ORACLE_HOME}/jdbc/lib/ojdbc6.jar:${ORACLE_HOME}/jdbc/lib/ojdbc14.jar:${ORACLE_HOME}/jdbc/lib/nls_charset12.jar;
CLASSPATH=$CLASSPATH:/export/home/gs806e/tops/jconn2.jar:.;
export CLASSPATH
I have multiple jars in a folder. The below command worked for me in JDK1.8 to include all jars present in the folder. Please note that to include in quotes if you have a space in the classpath
Windows
Compiling: javac -classpath "C:\My Jars\sdk\lib\*" c:\programs\MyProgram.java
Running: java -classpath "C:\My Jars\sdk\lib\*;c:\programs" MyProgram
Linux
Compiling: javac -classpath "/home/guestuser/My Jars/sdk/lib/*" MyProgram.java
Running: java -classpath "/home/guestuser/My Jars/sdk/lib/*:/home/guestuser/programs" MyProgram
Order of arguments to java command is also important:
c:\projects\CloudMirror>java Javaside -cp "jna-5.6.0.jar;.\"
Error: Unable to initialize main class Javaside
Caused by: java.lang.NoClassDefFoundError: com/sun/jna/Callback
versus
c:\projects\CloudMirror>java -cp "jna-5.6.0.jar;.\" Javaside
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable

javah issue Android Ndk in Linux

I am using Ubuntu Linux 32bit system, in terminal it shows no class specified
sanidhya09#sanidhya09:~/workspace/NdkFooActivity$ javah -jni
-classpath adt-bundle-linux-x86/sdk/platforms/android-4.2/android.jar;bin/classes/
-d jni/ com.example.NdkFooactivity Error: no classes specified bash: bin/classes/: Is a directory
even i have tried this
sanidhya09#sanidhya09:~/workspace/NdkFooActivity/bin/classes$ javah
-jni -classpath adt-bundle-linux-x86/sdk/platforms/android-4.2/android.jar; com.example.NdkFooactivity.NdkFooActivity Error: no classes specified com.example.NdkFooactivity.NdkFooActivity: command not found
even i tried External tools configuration
where in argument section i wrote
-d /home/sanidhya09/workspace/NdkFooActivity/jni -classpath /home/sanidhya09/adt-bundle-linux-x86/sdk/platforms/android-4.2/android.jar:/home/sanidhya09/workspace/NdkFooActivity/bin/classes com.example.NdkFooactivity
even in eclipse i get error saying
make:
[HelloJni] Error 127 HelloJni C/C++ Problem
sanidhya09#sanidhya09:~/workspace/NdkFooActivity$ javah -jni -classpath bin/classes:~/adt-bundle-linux-x86/sdk/platforms/android-16/android.jar com.example.NdkFooactivity.NdkFooActivity
should be fine, assuming your app package is com.example.NdkFooactivity and the class you are interested in is NdkFooActivity.
Note that you must pass the path to android.jar you actually used to compile. In my SDK, the directory is called android-16, not android-4.2. Also, you need to have the bin/classes directory in classpath. You may need more jars in your classpath.
But there is one more thing that I would like to add. (And which has taken up most of my morning solving that)
While specifying the classpath = Refrain from using ./bin/classes:~/ProjectFolder/bin/classes ( the tilde representing the Home directory)
But use the "../../" to switch directories. For some reason javah doesn't recognizes the tilde operator for the home directory.
Also one other thing if the class has a dependency on other project then you would need that as well in the classpath
user#laptop:~/SomeProject javah -classpath ./bin/classes:../<Whereever the path is>/SomeOtherDependentProject:../<Path to android-sdk>/android.jar <Qualified class path>

Compiling java file from different directory

I am very new to JAVA. I have written simple program (in Linux -VIM editor), compiled and executed it, everything is fine.
Now,I have moved that file to a different directory and am trying to compile(javac Myfile.java) it, but it throws an error message as javac-not found.
Can somebody explain what is the problem?
Your original question was not totally clear (since it did not contain the complete error message).
From your comment:
$ javac Example1.java
javac: file not found: Example1.java
Usage: javac <options> <source files> use -help for a list of possible options
So, javac did not find your file example java.
Normally, you should not have to set the CLASSPATH (use export CLASSPATH= in bash), and javac would search the source in the current directory. Is your Example1.java in the current directory? (Type ls and look at the output.)
If not, you should give the path to this file to javac as a parameter ... but it really is better so simply move to the right directory with cd.
If you are using packages, position your shell to the directory on top of the package directory hierarchy, and call the compiler with the relative filename from there.
Edit, since I see the next questions coming:
The compiler will put the resulting class files in the output directory tree given by the -d parameter (or the current directory, if not given), by their package structure, so make sure you search them there later (when invoking the program).
If the compiler needs other classes to compiler the files indicated in the command line, it searches class files in the classpath (given by the -classpath or -cp option, or by the CLASSPATH environment variable, or the current directory) and source files in the sourcepath (given by the -sourcepath option or the classpath if no sourcepath is set). If for a needed both exist and the source file is newer, it is recompiled too. (They are searched according to the package-structure, too.)
So in this case you should make sure to pass the -sourcepath option so the compiler can find your other source files.
set the classpath and path properly and check whether its working fine.
USAGE:
SET CLASSPATH=%<CLASSPATH>%
SET PATH=%<PATH_WHERE_JDKS_BIN_LOCATED>%
The path environment variable must point to the bin directory in the jdk installation...
USAGE:
Variable : JAVA_HOME
Value : C:\Program Files\Java\jdk1.5.0\bin;.
Variable: PATH
Value : C:\Program Files\Java\jdk1.5.0\lib
System Variables :
Variable : PATH (This will be there already)
Value : %JAVA_HOME%\bin;
Since the file is not in current directory do the below at the prompt
$cd home/kiddosr/Kiddo/Java_Programs/ and press enter
home/kiddosr/Kiddo/Java_Programs at this point of time type javac Example1.java

Get Rhino JS to see Java class

I'm playing with Rhino, and I've had success using Java classes from the stdlib, but not from Java code I compiled here.
For example, this works fine:
print(new java.util.Date());
But with NanoHTTPD (single .java file, no namespace, same folder), I'm having no luck at all:
js> new Packages.NanoHTTPD()
js: "<stdin>", line 4: uncaught JavaScript runtime exception: TypeError: [JavaPackage NanoHTTPD] is not a function, it is object.
at <stdin>:4
I'm sure it's something simple. What am I missing?
EDIT: I'm launching it like this:
$ CLASSPATH=. java -jar rhino.jar
or this:
$ java -classpath . -jar rhino.jar
Or I moved NanoHTTPD.java into the folder "./nano", added package nano; to the top of the file, compiled it, and then replaced "." with "nano" in the above classpath assignments.
Any way I do it, from in the interpreter I see:
js> java.lang.System.getProperty("java.class.path")
/Users/me/blah/rhino.jar
You need to run Rhino like this:
java -cp /path/to/rhino/js.jar:. org.mozilla.javascript.tools.shell.Main
This adds the current directory to the classpath. Using -jar clobbers the classpath. (The classpath separator depends on your OS.)
Then try
js> Packages.NanoHTTPD
[JavaClass NanoHTTPD]
If it says [JavaPackage NanoHTTPD], it means it hasn't found a class by that name.
You can't instantiate NanoHTTPD anyways, so I'm guessing you want to try Packages.NanoHTTPD.main([]) or something.
In my Linux, I found that the command 'rhino' is a shell script that runs 'org.mozilla.javascript.shell.Main' with the option '-classpath'. You can edit the file to include the path to your class.
I think the script is self explanatory.
If you use Linux, type:
less `which rhino`
If you don't plan to use your own clases in Rhino usually you run it in following way:java -jar ./js.jar
The problem to use the -jar switch is that you can't define classpath in this case and without setting classpath you can't access to your own packages and classes.To be able to set classpath you need to run Rhino using -cp switch. In this case you set your classpath by -cp switch which shall include package of Rhino and your packages and also you need pass Rhino's main class path inside the package (org.mozilla.javascript.tools.shell.Main)
Here is an example how to add your own packages to Rhino classpath:
Suppose you have your class mypackage.myclass placed in mylib.jar If you want to get this class available in your Rhino session you need to run Rhino in following way:
java -cp "./js.jar;../mylib.jar" org.mozilla.javascript.tools.shell.MainThen you can access to your class:jc> mc_obj = new Packages.mypackage.myclass()
Ensure that the current directory is included in your classpath. The default classpath is the current directory but if the classpath has been set to something else (say by the rhino startup script) then you could run into this.
You might also try placing your test class in a package just to see if it has some quirk with top-level classes.

Categories