相信大家在开发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宠坏了)很简单的两个包,你也可以试试。
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宠坏了)很简单的两个包,你也可以试试。
public static Class<?> forName(String className)
throws ClassNotFoundException所以在用该方法是要捕获异常ClassNotFoundException
你cd到当前路径java -jar xxx.jar试试
你cd到当前路径java -jar xxx.jar试试同样的结果
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下)
Main-Class: vdo.test.one.TestOne
Import-Package: vdo.test.two
Export-Package: vdo.test.one
Class-Path: testtwo.jar
增加最后那行就行
可以运行了,太感谢了。不过随之而来,又有两个问题:
1. 要是需要多个jar文件呢?(比如:不仅需要testtwo,还要testthree...)
2. 那命令行中的-cp /-classpath 又作什么用呢?
Class-Path: testtwo.jar testthree.jar testfour.jar就可以
很多人都跟我一样吧。谢谢 米。也很惭愧,
如果有时间的话,我会常来帮助其他人,如果帮得到的话。再次感谢 米。