从java程序执行JAR中的java类
我的问题是:
我有一个 test.java 类,它是主类。 JAR 文件中还存在一个类(非主类)。现在我想从 JAR 外部的主类编译并执行 JAR 中的演示类。请解释原因。
public class test
{
public static void main(String args[])
{
demo d1 = new demo();
demo d2 = new demo("message passed from main class");
}
}
public class demo
{
demo()}
System.out.println("message in demo class");
}
demo(String str)
{
System.out.println(str);
}}
My Question is:
I have a test.java class which is the main class. There is one more class(non-main class) which is present in JAR file. Now i want to compile and execute demo class present in JAR from the main class present outside the JAR. Please explain why.
public class test
{
public static void main(String args[])
{
demo d1 = new demo();
demo d2 = new demo("message passed from main class");
}
}
public class demo
{
demo()}
System.out.println("message in demo class");
}
demo(String str)
{
System.out.println(str);
}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看这个:在 JAR 文件中打包程序
主类和 JAR 文件准备就绪,您只需在类路径上运行带有 JAR 文件的主类,Java 就会找到它。假设
demo
类位于demo.jar
中,并且您的主类是test
(如您的示例所示):Have a look at this: Packaging Programs in JAR Files
Once you have both your main class and JAR file ready, you can simply run the main class with the JAR file on the classpath and Java will find it. Assuming the
demo
class is indemo.jar
and your main class istest
(as in your example):我猜正确的答案是“使用 ant”,但是:
然后,
如果您打算对此进行扩展,并且继续不使用 ant,您可能希望您的构建系统在出现错误时停止,并且会注意到“ javac' 出错时不会返回非零值。将其 stderr 通过管道传输到临时文件,然后根据 grep 该文件的非零返回退出。例如,来自无法使用 ant 的设备上构建脚本:
I guess the proper answer us 'use ant', but:
and then,
If you intend to expand on this, and continue not to use ant, you'll likely want your build system to stop on an error, and will notice that 'javac' doesn't return non-zero on error. Pipe its stderr to a temporary file and then quit depending on grep's non-zero return of that file. e.g., from an on-device build script that cannot use ant:
简而言之,如果您想在 java 中使用任何
类
,那么该类必须存在于class-path
中因为当您运行程序时,所需的所有
类
总是在类路径
中查找..所以你必须设置你的
demo.jar
没有办法设置类路径,看看这个如何设置类路径
或者简单地你可以使用
java
参数-cp
做另一个选项Simply if you want to use any
class in java
then that class must be present inclass-path
because when you run your program then all
class
needed for that is always looking inclass path
..So you have to set class-path of your
demo.jar
There is no of ways to set class path take a look of this How set class path
or simply you can do another option use
java
parameter-cp