简体   繁体   English

java从同一个包内的另一个类调用一个类

[英]java calling a class from another class within same package

So I was following this tutorial: https://spring.io/guides/gs/maven/所以我正在关注本教程: https : //spring.io/guides/gs/maven/

I cloned their repositories for the software for fear of mistyping something.我为软件克隆了他们的存储库,因为害怕输入错误。 The code does not work when I compile Greeter.java using javac and then use java to run HelloWorld.java file It gives me the following error:当我使用javac编译 Greeter.java 然后使用java运行 HelloWorld.java 文件时,代码不起作用它给了我以下错误:

HelloWorld.java:5: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:5: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
2 errors

I tried explicitly importing Greeter into HelloWorld using ìmport hello.Greeter The code works fine when I run it without the package hello;我尝试使用ìmport hello.Greeter将 Greeter 显式导入到 HelloWorld 中。当我在没有package hello;情况下运行它时,代码工作正常package hello; statements.声明。

Any idea why I am getting this error??知道为什么我会收到此错误吗?

So I followed through with the tutorial and using mvn package command and the jar file generated the project works.所以我按照教程并使用mvn package命令和 jar 文件生成了项目工作。

So is this issue with trying to compile it with java command in the command line.尝试在命令行中使用 java 命令编译它的问题也是如此。

Adding directory structure of the project添加项目的目录结构

pom.xml src     target

./src:
main

./src/main:
java

./src/main/java:
hello

./src/main/java/hello:
Greeter.java    HelloWorld.java


I assume you try to compile the sources while you're in the directory src/test/java/hello .我假设您在src/test/java/hello目录中尝试编译源代码。 That's the wrong directory, you have to do it from directory src/test/java and pass the directory (ie package) to the compiler, eg那是错误的目录,您必须从目录src/test/java并将目录(即包)传递给编译器,例如

javac hello/*.java

Another reason might be that you haven't compiled Greeter.java , so the compiler doesn't find the class-file while compiling Hello.java .另一个原因可能是您尚未编译Greeter.java ,因此编译器在编译Hello.java找不到类文件。 Above command should solve that.上面的命令应该可以解决这个问题。

If you have a main method in hello run java hello/name-of-file.java to run your main method.如果您在 hello 中有一个 main 方法,请运行java hello/name-of-file.java来运行您的 main 方法。

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

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