java.lang.NoClassDefFoundError. Class not found during runtime.

拟墨画扇 提交于 2019-12-13 09:23:59

问题


I am working on eclipse, and I have the need to use external library's. For example Jsoup and JXL.

Now what I have done so far is: First created a "lib" folder in my project folder. Afterwards in eclipse, click on project properties, Libraries tab, add external jar and added the jar in the lib folder.

So this solve my compilation issue. Now, when I run the program (I go to project/bin and in the console execute: java ProgramName ; I get

java.lang.NoClassDefFoundError: 

Now to testing, I added the Jar file to the folder where Main.java is and Now, I have been able to run the program doing the following:

javac -classpath ./path/to/jar Main.java
java -classpath ./path/to/jar:. Main  

And this works.

So the first thing that comes to mind is that I have to tell java where to find the respective libraries. If this is correct? How do I do it?

java -cp ???(dont know what to put here)

But moreover. I have another issue. I am writing this program in a computer, but I am going to use it in other which probably don't have those libraries. How do I solve this issue?


回答1:


I like to use something like the following:

java -cp myjar.jar;lib/*.jar com.foo.bar.MyClass

This adds not only my jar to the classpath but those in the lib directory as well.

If you want to run your jar on another computer, you will need those jars as well, you cant just have your jar. Why not just also package your lib directory along with it?




回答2:


To get your program to run you have two paths to worry about

  1. The path to the jar files that are your applications dependencies (like jsoup.jar) (lets call this lib)
  2. The path to the directory containing the classes of your app (lets call this classes)

The general form of the command line you need is:

java -cp lib/jsoup.jar:classes Main

If you have more libs

java -cp lib/jsoup.jar:lib/jxl.jar:classes Main

A general note on packaging your app for release to other computers. You might want to consider making a jar of your own app, probably best done using http://ant.apache.org/manual/Tasks/jar.html

Another option is to produce a "one jar", which makes one large jar, bundling in all the classes you need from your libs and all the classes in your app. You can then make the jar executable for a nice out of the box solution. Have a look at http://one-jar.sourceforge.net/ and https://code.google.com/p/jarjar/




回答3:


if you have this structure:

project folder
... code
... libs

then from the code folder:

javac -cp .;../libs/*.jar yourmainclass.java
java -cp  .;../libs/*.jar yourmainclass

When you need to compile and run this project, take all the folder and do the same in other machine.



来源:https://stackoverflow.com/questions/16174252/java-lang-noclassdeffounderror-class-not-found-during-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!