无法通过命令行启动 Java 应用程序

Can not start Java application via commandline

所以我在 eclipse 中有一个 Maven 项目,我通常可以通过 运行 as> Java 应用程序启动。但是,如果我尝试通过 "java TestServer" 从命令行从目标目录启动 class 文件,它将无法工作。它说它无法找到或加载主 class。如果我用一个简单的虚拟 hello world 替换源代码并执行它就可以正常工作。

代码有两个maven依赖。

简单虚拟:

public class HelloWorld {

    public static void main(String[] args){
        System.out.println("hello world!");

    }
}

为什么会这样?嵌套class有问题吗?为什么不能为代码找到一个主要 class,而是为一个小的虚拟人找到?

The problem is the classpath.

Maven is not responsible for 运行 the project from Eclipse workspace because Eclipse holds its own .project file, which contains all classpath entries. When you use Run As, Eclipse just uses all classpath configurations of its .project file.

To start the java program from console, you need to set the classpath to your bin or target directory and to all libraries ('jar') which are referenced by your project. After setting the classpath correctly you can start your program with java <qualified classname>. Starting the program this way does not use any of Maven's functionallity yet at all.

Have a look here to use Maven https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

Maven will create a library jar which contains all 类 of your project. You can set the classpath to the generated library and start your programm using java <qualified classname>

EDIT due to comment

Here is an example for setting the classpath using the Windows OS 安慰。 You can put this line also into an appropriate Windows batch (.bat) file and start your program,

set classpath = .;log4j.jar;lib/any-other-lib.jar
java org.<whatever>.MyProgram

for further information for setting the classpath on other OS's you may also have a look at setting Java Classpath in linux?