joeferner / node-java

Bridge API to connect with existing Java APIs.
MIT License
1.87k stars 280 forks source link

Could not create class error instructions #596

Open velara3 opened 5 months ago

velara3 commented 5 months ago

I am trying to use this project with my nodejs project instead of a java project and in my nodejs project I have the basic example code from this project working and it is creating an array list.

But now I would like to include a library / jar from the java project and I am getting an error:

Error: Could not create class ClassFromJavaProjectInJar
java.lang.NoClassDefFoundError: ClassFromJavaProjectInJar

I looked in my Java project and I don't see the libraries. I found out they are in the /user/.m2 directory. This is where Maven caches them.

I saw another post somewhere that someone else solved the issue by copying their libraries and jars into their nodejs project. I could do this. But is there a better way?

I don't believe I need to use Maven for this project but I haven't got that far.

I saw a note about a java-maven package but none of it made sense. I Have one library / jar I want to use and that's it.

-- Also, as a side note I think this error or this issue should be part of the instructions. Also, thank you for this project.

velara3 commented 5 months ago

Well I think I figured out one way to do it. I copied the jar into the nodejs project at the root of the project. Then I added the jar to the class path like so:

var java = require("java");
java.classpath.push("mylibrary.jar");

Then it seems I can use two methods.

The import method:

var MyClass = java.import("com.something.path.MyClass");
var myClassInstance = new MyClass();

The new instance method:

var myClassInstance = java.newInstanceSync("com.something.path.MyClass");
velara3 commented 5 months ago

Please consider adding this error message and these instructions to the main instructions page as the user may be migrating from a Java project.