简体   繁体   English

从同一个包中的类访问静态方法。 主要()

[英]Access static method from class in same package via. main()

I've never tried to do this before and am a little flummoxed. 我以前从来没有试过这样做,而且有点沮丧。 Two classes in the same package: 同一个包中的两个类:

package test;

public class One {
    public static String test () { return "hello world"; }
}   

and: 和:

package test;

public class Two {
    public static void main (String[] args) {
        System.out.println(One.test());
    }
}

If I try and javac Two.java inside the test/ directory, I get "cannot find symbol" for One. 如果我尝试和javac Two.java test /目录里面 ,我得到“无法找到符号”为一体。 However, if I do it from the parent directory, javac test/Two , it compiles, and can then be run java test/Two -- but again not from inside (throws a NoClassDefFoundError saying the proper name of the class is test/Two , not Test ). 但是,如果我从父目录执行它, javac test/Two ,它编译,然后可以运行java test/Two - 但不能再从内部(抛出NoClassDefFoundError,说该类的正确名称是test/Two ,而不是Test )。

Not a big deal, but curious if there is a better way around it, and if anyone can help me understand the issue. 没什么大不了的,但是如果周围有更好的方法就好奇,如果有人能帮助我理解这个问题。 I actually do not need "Two" to be a formal member of the test package, I just need to have it in the same directory and compilable there. 我实际上不需要“Two”成为测试包的正式成员,我只需要将它放在同一目录中并在那里编译。

You need to compile from the parent directory with: 您需要从父目录编译

javac test/Two.java test/One.java

(You might also want to use -d to say where you want the class files to end up. Note that you could just compile test/One.java and let the compiler find the class it depends on, but I find it cleaner to just specify all the source code you want to compile.) (您可能还想使用-d来说明您希望类文件最终的位置。请注意,您可以编译test/One.java并让编译器找到它依赖的类,但我觉得它更干净指定要编译的所有源代码。)

And run with the package-qualified class name: 并与全限定类名来运行

java test.Two

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

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