【问题标题】:Not able to access imported class using * wildcard but able to use same class when imported with full qualified name无法使用 * 通配符访问导入的类,但在使用完整限定名导入时能够使用相同的类
【发布时间】:2023-11-05 19:23:01
【问题描述】:
  • 我是 Java 新手,请帮助我
  • 我在导入语句中使用 * 通配符时遇到问题
  • 我使用 javac -d 编译了 javatesting1 类。 javatesting1.java 并且还得到了 test1 包中的 .class 文件
  • 这是我的文件夹结构click on this image
  • 当我使用带 * 的 import 语句编译 javatesting2 时,出现以下错误
    javac javatesting2.java
    javatesting2.java:2: error: cannot access javatesting1
    class testingclass extends javatesting1
                               ^
    bad source file: .\javatesting1.java
    file does not contain class javatesting1
    Please remove or make sure it appears in the correct subdirectory of the sourcepath.


    javatesting2.java:6: error: cannot find symbol
        System.out.println(a);
                           ^
    symbol:   variable a
    location: class testingclass

    2 errors

这是我的代码

    package test1;
    public class javatesting1
    {
         protected int a=45;
         int b=78;
    }
    //I am not able to use the javatesting1 class when i use test1.* instead of test1.javatesting1
    
    // the below code is on another file in the same directory
    import test1.javatesting1;
    class testingclass extends javatesting1
    {
        public void meth1()
        {
            System.out.println(a);
           // System.out.println(b);
        }
    }
    public class javatesting2
    { 
        public static void main(String [] args)
        {
                  testingclass obj=new testingclass();
                  obj.meth1();
        }
    }

【问题讨论】:

    标签: java import package wildcard importerror


    【解决方案1】:

    您好,欢迎来到 Stack Overflow!

    由于您将类 javatesting1 声明在包 test1 中,Java 期望在以包命名的文件夹中找到该类,以便对其进行扫描(使用通配符)。 我已经测试了您的代码,使用通配符 * 导入,具有这样的文件夹结构

    文件夹

    • javatesting2.java
    • 测试1
      • javatesting1.java

    尝试编辑您的文件夹结构。

    另外请尽量遵守编码约定:类名应使用 CamelCase 命名,例如JavaTesting1

    【讨论】:

    • 感谢您的回复我的文件夹结构与您所说的相同,并且出现相同的错误我已将文件夹结构包含在图像中,请检查它
    • 你必须把javatesting1.javainside文件夹test1:因为你正在编译源代码,Java希望在文件夹中找到.java文件
    • 感谢 siberio 花时间澄清我的问题,它现在可以正常工作,没有任何错误,但我仍然有点怀疑它是否正在检查源代码,那么为什么在没有通配符的情况下导入 test1.javatesting1 是即使源代码不存在于 test1 包中也能正常工作是它试图首先检查 test1 包中的源代码,然后在找不到它之后,它试图在当前文件夹中找到它是正确的吗这是我的假设顺便说一句?跨度>
    • 有可能。这是取自 Java 文档,虽然 You should arrange source files in a directory tree that reflects their package tree. By default, the compiler puts each class file in the same directory as its source file. docs.oracle.com/javase/6/docs/technotes/tools/windows/…
    • 感谢您对 Siberio 的所有帮助,我的疑问已得到澄清?