【问题标题】:Importing an Entire JAR Library in a Class在类中导入整个 JAR 库
【发布时间】:2013-01-08 13:21:36
【问题描述】:

请原谅我对 Java 导入的困惑——我来自 Python 背景。

我有一些使用 itext 库的代码:

public static void makeADoc (Person p, String outfile) throws DocumentException,FileNotFoundException{
        Document document = new Document;
        PdfWriter.getInstance(document, new FileOutputStream(outfile));
        document.open();
        document.add(new Paragraph("Hello " + p.getFirst() + ",\n" + "You've just won the lotto!"));
        document.close();
    }

我已将适用的 itext-pdf jar 文件添加到项目的路径中。我已经在这个类的开头使用通配符导入语句导入了整个库:

import com.itextpdf.*;

然而,对于 Document 对象和 DocumentException 和 FileNotFound Exception 对象,Eclipse 仍然给我带有红色下划线的错误。我可以选择从 itextpdf 导入 Document 类,但我的通配符语句似乎应该涵盖了这一点。这是怎么回事?

【问题讨论】:

  • 在 Eclipse 中,按Ctrl-o,这将执行 Organize Imports,这将解决您的头痛问题。如果存在名称冲突,您只需选择正确的类名。

标签: java eclipse itext


【解决方案1】:

FileNotFoundException 不是来自 itextpdf 包,而是来自包 java.io。因此,您还应该添加此导入语句。另请记住,使用此类通配符 import 语句有时被认为是不好的做法,因为它可能会使您的命名空间变得混乱。

此外,通过您的通配符语句,您可以导入包com.itextpdf 中的所有类。但是,DocumentException 类在包com.itextpdf.text 中而不是com.itextpdf,因此您还必须添加此导入语句。请注意,在 Java 中没有子包的概念,尽管人类有时会使用这个类比。所以com.itextpdf.text 是一个与com.itextpdf 完全不同的包。

【讨论】:

  • 那么我最好一次导入一个类吗?例如,如果我实现了 Document Exception 和 PdfWriter,我只是返回到它们,Command-1 它们,然后从 itext 库中导入这些类,而不是尝试导入一个包罗万象的库?
  • 一般来说,最好根据需要导入每个类,而不是使用通配符。但是没有规则没有例外:) 也看看这个问题:stackoverflow.com/questions/147454/…
猜你喜欢
  • 1970-01-01
  • 2014-04-29
  • 2021-02-18
  • 2017-03-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2012-07-01
  • 2013-09-15
相关资源
最近更新 更多