相信大家在开发java app的时候,都是使用各种IDE来配置和运行。我也是,直到碰到Class.forName()抛出异常,才意识到写了一年的程序,其实连一个最常识的问题都没搞清楚,希望大家能过来顶下:转化成如下简要步骤:包testone.jar testtwo.jar,两个包都有相应的MF文件,而且没问题
testone中的TestOne.main() 会初始化testtwo中的TestTwo类的实例命令行中使用:java -classpath .;./testtwo.jar;%CLASSPATH% -jar testone.jar
结果:Exception in thread "main" java.lang.NoClassDefFoundError: vdo/test/two/TestTwo
         at vdo.test.one.TestOne.main(./vdo/test/one/TestOne.java:9)源代码绝对没问题,该import的,都import了。
我该怎么在命令行下运行包 testone.jar ???????
(感觉被Eclipse宠坏了)很简单的两个包,你也可以试试。

解决方案 »

  1.   

    你仔细看看文档
    public static Class<?> forName(String className)
                            throws ClassNotFoundException所以在用该方法是要捕获异常ClassNotFoundException
      

  2.   

    这种异常捕获了,没什么实质意义。你不能挽回什么,只能知道你想得到的类得不到了,仅此而已。顶多就是继续让app跑下去。注意:我现在的问题跟Class.forName 无关。只是由它引出的而已。
      

  3.   

    可能是classpath参数的问题
    你cd到当前路径java -jar xxx.jar试试
      

  4.   

    可能是classpath参数的问题
    你cd到当前路径java -jar xxx.jar试试同样的结果
      

  5.   

    好了,我把程序搬出来吧:
    TestOne.java:
    package vdo.test.one;import vdo.test.two.TestTwo;public class TestOne{   public static void main(String[] args)
       {
          TestTwo t = new TestTwo();
          System.out.println(t.toString());
       }
    }testone.mf:Manifest-Version: 1.0
    Main-Class: vdo.test.one.TestOne
    Import-Package: vdo.test.two
    Export-Package: vdo.test.one------------------------------------
    TestTwo.java:
    package vdo.test.two;public class TestTwo{   public String toString()
       {
          return "This test is first.";
       }
    }testtwo.mf:Manifest-Version: 1.0
    Main-Class: vdo.test.two.TestTwo
    Export-Package: vdo.test.two使用以上四个文件打包,并运行吧。(在console下)
      

  6.   

    修改testone.mf:Manifest-Version: 1.0
    Main-Class: vdo.test.one.TestOne
    Import-Package: vdo.test.two
    Export-Package: vdo.test.one
    Class-Path: testtwo.jar
    增加最后那行就行
      

  7.   

    to ChDw(米):
    可以运行了,太感谢了。不过随之而来,又有两个问题:
    1. 要是需要多个jar文件呢?(比如:不仅需要testtwo,还要testthree...)
    2. 那命令行中的-cp /-classpath 又作什么用呢?
      

  8.   

    在使用-jar的时候,java.exe似乎是忽略其中设置的classpath环境变量你只能在上述的MF文件中增加声明
    Class-Path: testtwo.jar testthree.jar testfour.jar就可以
      

  9.   

    感谢 ChDw(米)。今天这一天没白耗。记得读大学的时候经常上CSDN,工作后就很少了。
    很多人都跟我一样吧。谢谢 米。也很惭愧,
    如果有时间的话,我会常来帮助其他人,如果帮得到的话。再次感谢 米。