I want to create c library and use it in my java code on an Linux OS. I'm trying to understand and implement natural library concept.
I'm following this tutorial
http://diglib.stanford.edu:8091/~testbed/doc/JavaUsage/JNI/tutorial.txt
Which is helpful me to understand concept a little. However, I get errors when I try to do it myself. I searced for errors I am getting but none of solutions helped.
Main class code and class for natural library I wrote is as follows:
package natLib;
import natLib.getKeyPressed;
public class main {
public static void main(String[] args) {
getKeyPressed natlab=new getKeyPressed();
char c=natlab.keyboardPressedKey();
}
}
package natLib;
public class getKeyPressed {
static {
System.loadLibrary("natlab");
}
public native char keyboardPressedKey();
}
when I write "javac main.java"
I get errors like
"main.java:6: error: cannot find symbol
getKeyPressed natlab=new getKeyPressed();"
And when I skip for main and just do javac prcess for class with native method, try to obtain a header file
javah -jni getKeyPressed.class
Although there is a file as getKeyPressed.class, I get errors like:
"Exception in thread "main" java.lang.IllegalArgumentException: Not a valid class name: getKeyPressed.class"
I try it without .class extention it says
"Error: Could not find class file for 'getKeyPressed'."
It says that even when I make getKeyPressed class file by copying getKeyPressed.class.
It seems I am making a major mistake, any suggestions to solve this?
javah expects a fully qualified classname. (e.g. natLib.getKeyPressed, not just getKeyPressed)
Related
I'm putting together some (Python) scripts to help me automate some of my grading of hundreds of simple student Java repos. Not all of them have the same directory structure or naming of files. I've traversed them all and compiled them and if I make assumptions I can run them and test them, etc. But I'd like to know if there's a way I could find the "main" .class that has the main() method in it, so that I don't have to make assumptions about their file naming (which wouldn't work all the time anyway).
I'm aware of reflection, so yes, I know I could write another simple helper Java program to assist me in identifying it myself. But I was wondering if anything already exists (java command line option, tool from the jdk, etc.) to test a .class file to see if it is has the main() method in it.
I was wondering if anything already exists (java command line option, tool from the JDK, etc.) to test a .class file to see if it is has the main() method in it.
There is no tool or option in Java SE that does that directly.
I know I could write another simple helper Java program to assist me ...
It would be simpler to write a shell script that iterates a file tree, finds .class files, calls javap on them, and greps for a method with the appropriate main method signature.
Or you could do something similar on the source code tree.
(In retrospect, you should have set the assignment requirements so that the students had to use a specified class and package name for the class containing their main method. But it is too late for that now ...)
In the C++ days, distributing the headers files to use a shared object file was a big deal. People would get one or the other without both, and there was always the chance you'd get mis-matched versions.
Java fixed that with javap which prints the methods (and other major interfaces) of a compiled .class file.
To test if a class file has a main, run
javap SomeFile.class
which will list all public interfaces. Within that list, see if it has the "main entry point"
public static void main(java.lang.String[])
Now to handle this in mass, simply create a Python script that:
Locates all the relevant classes.
Runs javap on the class.
Reads the output for a method that matches (at the beginning, as there can be a variable number of Exceptions at the end "public static void main(java.lang.String[])
And you'll find all entry points.
Keep in mind that sometimes a single library or JAR file has many entry points, some of which are not intended as the primary entry point.
Well simply calling java -cp . <file> will either completely blow out if the class doesn't have a main method or will run the relevant code. Now, if the code fails to run right and errors out you may see it as the same effect as not having a main method.
public class HasMain {
public static void main(String[] args) {
System.out.println("Hit main");
}
}
public class HasDoIt {
public static void doIt(String[] args) {
System.out.println("Hit doIt");
}
}
public class WillBlowUp {
public static void main(String[] args) {
System.out.println("Hit blowUp");
throw new IllegalStateException("oops");
}
}
Using PowerShell:
PS D:\Development\sandbox> javac HasMain.java
PS D:\Development\sandbox> javac HasDoIt.java
PS D:\Development\sandbox> javac WillBlowUp.java
PS D:\Development\sandbox> java -cp . HasMain
Hit main
PS D:\Development\sandbox> $?
True
PS D:\Development\sandbox> java -cp . HasDoIt
Error: Main method not found in class HasDoIt, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
PS D:\Development\sandbox> $?
False
PS D:\Development\sandbox> java -cp . WillBlowUp
Hit blowUp
Exception in thread "main" java.lang.IllegalStateException: oops
at WillBlowUp.main(WillBlowUp.java:4)
PS D:\Development\sandbox> $?
False
So simply checking return values could be a quick way to test if the class has what you want, albeit any exit(1) type return will throw a false-false
So I have followed this Swig tutorial to generate JNI proxy class and shared library. In result I have got libexmple.so file.
In Building a Java module tutorial section you can see.
$ swig -java example.i
$ gcc -c example.c example_wrap.c -I/c/jdk1.3.1/include -I/c/jdk1.3.1/include/win32
$ gcc -shared example.o example_wrap.o -mno-cygwin -Wl,--add-stdcall-alias -o example.dll
$ cat main.java
public class main {
public static void main(String argv[]) {
System.loadLibrary("example");
System.out.println(example.getMy_variable());
System.out.println(example.fact(5));
System.out.println(example.get_time());
}
}
$ javac main.java
$ java main
3.0
120
Mon Mar 4 18:20:31 2002
3.0, 120 and Mon Mar 4 18:20:31 2002 are functions results.
Honestly I didnt even expected it to compile, but it did and it runs without problem when i do java main.
So my 1 question is? How does java know what "example" is in println method call
System.out.println(example.getMy_variable());
when I try to compile it thourgh Intellij IDE, naturaly it throws me an error
"could not find symbol example" as i should throw.
2ndly when i try to use this library in this way
public class Main {
static {
try {
System.loadLibrary("example");
System.out.println("lib initialized");
} catch (Exception e) {
System.out.println(e.toString());
}
}
public static native void My_variable_set(double jarg1);
public static native double My_variable_get();
public static native int fact(int jarg1);
public static native int my_mod(int jarg1, int jarg2);
public static native String get_time();
public static void main(String args[]) {
try {
Main.fact(3);
System.out.println("method called successfully");
} catch (Exception e) {
System.out.println(e.toString());
}
}
i am getting
Exception in thread "main" java.lang.UnsatisfiedLinkError: test.Main.fact(I)I
when trying to call native method.
I am sure that lib is loaded properly (getting lib initialized log). When I tried to load non existence i got different error (class load exception)
java.lang.UnsatisfiedLinkError: no exampleld in java.library.path
Why does it even compile?
Because javac can see that main uses class example from the same package, and compiles it. Actually, it finds also the class exampleJNI, which is also auto-generated by swig, and is used in example.java.
How does java know what "example" is in println method call?
In Java, you don't need import for classes that are in the same package, that's how java knows to call example.getMy_variable().
when i try to use this library, I get exception
Your attempt to move the native methods from exampleJNI.java to main.java failed because with JNI, the name of the class is used to determine the name of the native function. You can see it if you look at the list of exported functions of example.dll.
If you want to use swig, just use the files it generated. If you want to understand better how JNI works, read the books or online documents, follow tutorials, etc. Don't try to use swig for what it is not: an introduction to JNI programming.
I'm trying to use JNI to access C++ methods from a Java class. I'm able to compile (both in Eclipse or on command line) my Java class fine, but on executing the class at runtime, I'm getting:
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.domain.services.CallServiceAPIS.createSession()I
at com.domain.services.CallServiceAPIS.createSession(Native Method)
at com.domain.services.CallServiceAPIS.main(CallServiceAPIS.java:18)
Java code is as follows:
package com.domain.services;
public class CallServiceAPIS {
static {
System.loadLibrary("service.client");
}
public native int createSession();
public static void main(String[] args) {
System.out.println(System.getProperty("java.library.path"));
new CallServiceAPIS().createSession();
}
}
I included the printout of the java.library.path just to make sure it's pointing to the correct location of the C++ library - and it is. I also tried setting the LD_LIBRARY_PATH in my Eclipse environment. But neither worked.
Note that the System.loadLibrary call IS working since 1) the code compiles and 2) the error occurs on line 18, which is the new CallServiceAPIs call.
C++ code:
int createSession(const PosServiceInfo info, const SessionArgs& args, Domain::UUID& uuidSession)
{
return int::undefined;
}
Any ideas?
Never mind. I realized that I was using the JNI interface incorrectly. I was thinking you could load an EXISTING C++ library using EXISTING C++ source. But you basically have to rewrite the existing code to make use of the JNI interface.
I have built a DLL which I am attempting to wrap Java code with, however I am having some troubles with running my Java program. I wrote a simple test DLL and Java program and am producing the same error, and although there are plenty of resources regarding NoClassDefFoundError online I can't seem to solve mine with any troubleshooting methods.
Here is my D:\Test1.Java file
public class Test1 {
static {
//System.loadLibrary("HeyLand");
System.load("D://HeyLand.dll");
}
public native void displayHeyLand();
public static void main (String[] args) {
Test1 t = new Test1();
t.displayHeyLand();
}
}
After compiling, attempting to run D:\Test1.classresults in the following:
D:\>java Test1.class
Exception in thread "main" java.lang.NoClassDefFoundError: Test1.class
Caused by: java.lang.ClassNotFoundException: Test1.class
at java.net.URLClassLoader.findClass(URLClassLoader.java:434)
at java.lang.ClassLoader.loadClass(ClassLoader.java:660)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:358)
at java.lang.ClassLoader.loadClass(ClassLoader.java:626)
Could not find the main class: Test1.class. Program will exit.
Why I am stumped :
1. I have set my classpath to be D:\, so I believe my class definition would be in the classpath, and I do not see how my compile-time and run-time classpaths could be any different.
2. I don't see how this could have anything to do with static initialization, and I believe the exception would look different.
Perhaps I'm just missing something incredibly simple, I am very newbie with Java.
Any help is greatly appreciated!
The classpath environmental variable is taking precedence over that in the java run command. You need to specify the class location (as well as removing the .class file extension)
java -cp . Test1
Java normal syntax for executing class file is
Java [<options>....} <class-name> [<arguments>....]
For example
java com.package.name.Test1
here how compiler works
1. Compiler search for complete class name
2. Load that class
3. check for main method - in the same class
4. Call main method with passed arguments in command line string.
Now following are the possibilities why your class may not found main method.
1 - forgot to include package name
I am new developer in java but I found when I run application using eclips or intellJ editor it gives different path and package name and execute code as I noticed it on command line edior. So make sure you are including package name
For example:
java com.package.name.Test1 instead of
java Test1
2. File name or pathname rather then class name
As I noticed output file is in different location. That why class file path was different.
java Test1.class
java com/package/name/Test1.class
3. Typo
also I noticed you are using
static {
//System.loadLibrary("HeyLand");
System.load("D://HeyLand.dll");
}
Is this function ? or constructor? If it is function then where is name of the function? You cant write code without any reference in classs
Here is the thing: I am trying to run the example program in the joda-time project.
The start of the Examples.java file looks like this:
package org.joda.example.time;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Instant;
/**
* Example code demonstrating how to use Joda-Time.
*
* #author Stephen Colebourne
*/
public class Examples {
public static void main(String[] args) throws Exception {
try {
new Examples().run();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
And all the classes for compiling this Example.java is in a joda-time-2.3.jar.
I can successfully compile this program by using
javac -cp somewhere/joda-time-2.3.jar Example.java
And it generate an Example.class, but I jut cannot execute that.
So far I have tried:
java Examples
java -cp somewhere/joda-time-2.3.jar Examples
java -cp somewhere/joda-time-2.3.jar org.joda.example.time.Examples
But they all generate this kind of errors:
Error: Could not find or load main class org.joda.example.time.Example
Error: Could not find or load main class Examples
And I've tried both in the org/joda/example/time folder and the parent folder of org
Anyone can give an instruction on how to execute that? Really appreciate it!
Error: Could not find or load main class org.joda.example.time.Example
public class Examples {
Name of your class is Examples not Example
EDIT
Sorry for late reply...
To execute specific Java program you need to bring control to root directory so if your class is in abc/newdir/Examples.java you need to use cd command (in windows) to lead control to root directory and than compile or you can defeneitly go for the suggestion of kogut.
C:/abc/newdir>java -cp somewhere/joda-time-2.3.jar Examples
Modify your classpath parameter, so it should include directory where Example.class was generated.
In case of out/org/joda/example/time/Example.class you need to use
java -cp somewhere/jodata-time-2.3.jar:out org.joda.example.time.Example