如何访问 .java 文件没有包语句的类? [英] How to access a class whose .java file has no package statement?

查看:108
本文介绍了如何访问 .java 文件没有包语句的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是对某事感到好奇.假设我有以下环境:

I'm just curious about something. Say I have the following environment:

文件夹结构-

projects \ prj1 \ src \ pkgs \ main (contains Main.java)
                             \ test (contains TestClass.java)

Main.java -

Main.java -

package pkgs.main;

import pkgs.test.TestClass;

class Main {
    public static void main(String[] args) {
        TestClass tc;
    }
}

基于Java shell的编译命令-

Java shell based compilation commmands -

javac -d ..\cls -sourcepath ..\src ..\src\pkgs\main\Main.java
java -classpath ..\cls pkgs.main.Main

如果我再创建一个名为 Default.java 的 .java 代码文件,它就没有包语句 -

If I then make a .java code file called Default.java, that doesn't have a package statement -

public class Default {}

然后把这个文件放到src文件夹下,Main.java这样的类文件怎么访问这个Default类呢?我尝试使用以下导入语句,但都不起作用,导致编译错误:

and place this file in the src folder, how can a class file such as Main.java access this Default class? I tried using the following import statements, but neither worked, causing compilation errors:

Main.java -

Main.java -

package pkgs.main;

// import Default;    (causes many compilation error messages)
// import .Default;   (causes "identifier expected" compilation error)

我还将 Default.java 文件从 src 文件夹移到包含 Main.java 的同一文件夹中,但这也不起作用.我很欣赏整个想法看起来很糟糕的设计,但我这样做只是为了更多地了解 package 和 import 语句的工作原理,以及项目文件夹结构.谢谢.

I also moved the Default.java file from the src folder, in to the same folder that contained Main.java, but that didn't work either. I appreciate that this whole idea seems like bad design, but I'm only doing it in order to learn a bit more about how the package and import statements work, alongside the project folder structure. Thanks.

推荐答案

为了避免两个间接步骤,接受的答案的本质是 根据规范:

To avoid two steps of indirection, the essence of the accepted answer is that according to the specification:

从未命名的包中导入类型是编译时错误.

It is a compile time error to import a type from the unnamed package.

这意味着如果您不在未命名(又名默认)包中,则无法访问未命名/默认包中的类,除非您准备转向反思.

Which means that if you're not in the unnamed (aka default) package, you can't reach classes in the unnamed/default package, unless you are prepared to turn to reflection.

但是,如果您在未命名/默认包中,则不需要导入任何内容,只需不要忘记设置类路径,例如javac -cp "."ABC.java

However, if you're in the unnamed/default package, you don't need to import anything, just don't forget to set the classpath, e.g. javac -cp "." ABC.java

这篇关于如何访问 .java 文件没有包语句的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆