简体   繁体   English

如何在LINUX上设置环境变量CLASSPATH和NoClassDefFoundError

[英]How to set environment variable CLASSPATH and NoClassDefFoundError on LINUX

I've been studying classpaths and came across a question. 我一直在研究类路径,遇到一个问题。 I used the code below: 我使用下面的代码:

class AAA 
{
    public AAA() 
    {
        System.out.println("AAA");
    }
}
class BBB 
{
    public BBB() 
    {
        System.out.println("BBB");
    }
}
class ABMain 
{
    public static void main(String[] args) 
    {
        AAA aaa=new AAA();
        BBB bbb=new BBB();
    }
}

On terminal, I did: 在终端上,我做了:

  1. javac ABMain.java javac ABMain.java
  2. mkdir sub mkdir子
  3. set CLASSPATH=.:.\\sub; 设置CLASSPATH =。:。\\ sub;
  4. move AAA.class .\\sub\\AAA.class 移动AAA.class。\\ sub \\ AAA.class
  5. move BBB.class .\\sub\\BBB.class 移动BBB.class。\\ sub \\ BBB.class
  6. java ABMain Java ABMain

When I checked the sub directory, I found that AAA.class and BBB.class were correctly moved, but when I try to run ABMain, I get the following: 当我检查子目录时,我发现AAA.class和BBB.class已正确移动,但是当我尝试运行ABMain时,得到以下信息:

Exception in thread "main" java.lang.NoClassDefFoundError: AAA at ABMain.main(ABMain.java:17) Caused by: java.lang.ClassNotFoundException: AAA at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more 线程“主”中的异常java.lang.NoClassDefFoundError:在ABMain.main处为AAA(ABMain.java:17)由以下原因引起:java.lang.ClassNotFoundException:在java.net.URLClassLoader.findClass(URLClassLoader.java:381)处为AAA在sun.misc.Launcher $ AppClassLoader.loadClass(Launcher.java:335)处的java.lang.ClassLoader.loadClass(ClassLoader.java:424)在java.lang.ClassLoader.loadClass(ClassLoader.java:357)... 1更多

Could you please comment on what I should change to make it work? 您能否评论一下我应该进行哪些更改才能使其正常工作? Thank you in advance. 先感谢您。

You need to import the package of sub in before ABMain class because how your ABMain would be able to know the location of AAA and BBB 您需要在ABMain类之前导入sub的包,因为ABMain将如何知道AAA和BBB的位置

I would suggest use before AAA Class and BBB class 我建议在AAA级和BBB级之前使用

package sub; 包子;

and import package by writing below code before ABMain class 通过在ABMain类之前编写以下代码来导入包

import sub.*; 进口分包*;

According to title, you use LINUX. 根据标题,您使用LINUX。 But your steps are for windows ecosystem. 但是您的步骤适用于Windows生态系统。 To correct the example, you should use direct slash as path delimiter, and add current dir as CLASSPATH alternative (to be able to load main class as well): 要更正示例,您应该使用直接斜杠作为路径定界符,并将当前目录添加为CLASSPATH替代项(以便也可以加载主类):

  1. javac ABMain.java
  2. mv AAA.class ./sub/AAA.class
  3. mv BBB.class ./sub/BBB.class
  4. java -cp ./sub:. ABMain

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM