Java Classpath Issue

一个人想着一个人 提交于 2019-12-02 11:54:06

You cannot add a single class in your classpath like this. You have 3 solutions:

  • add this class in the path of your other compiled classes (respecting the package naming of your directories)
  • add the root directory of this class in your classpath (in your case "C:\java\project\")
  • add this single class into a jar and add this jar to the classpath

For your problem, the thrird choice is cleaner: external dependencies normally are packaged into jar files.

First of all: the use of the CLASSPATH environment variable is very strongly discouraged. The best thing is for you to forget that it exists. Use the -cp command line switch or similar methods to set the classpath.

Second, the classpath entries each represent a place where the classloader will start looking for .class according to the package hierarchy, i.e. it will look for the class org.myCompany.Library in a subfolder org/myCompany in any of the classpath entries.

Therefore, if

  • you add a classpath entry C:\java\project\
  • and there is a class file C:\java\project\org\myCompany\Library.class
  • which is actually part of a package org.myCompany (capitalization matters here!)
  • and your MyApplication class has an import org.myCompany.Library;

Then it really should work.

If your .class file isn't in jar file, point your classpath to the parent dir where package of class resides, e.g., for class org.myCompany.Library, point your CP to directory containing org/myCompany.
If your .class file included into some jar file, add full path to that jar to your classpath.

If you compiled the class files to a different directory, the classpath needs to point to where the .class file is.

set CLASSPATH=C:\java\project\;

is correct assuming that that the class file is in the same directory as the .java source file.

Is there a problem locating the Library to the same root project where is your MyApplication class

Example, if:

c:/project/org/company/MyApplication.class

Can you locate the Library class into:

C:/project/org/myCompany/Library.class

please notice, that the folders org/myCompany and org/company are located under the same folder c:/project/.

Please notices that this solution works for you if the Library Class is only used by your application.

Edited Windows command prompt is tedious, after setting the classpath please close and re-open the Command Prompt, so it can see the new classpath's value.

For the classpath to work, you need to have a folder structure which matches the package hierarchy. So if your class is org.myCompany.Library, you must create a nested folder structure of C:\java\project\org\myCompany and place your Library class file in the myCompany folder. Then set the class path to C:\java\project\

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