java - Eclipse JDT 编译器说方法未定义,但 Eclipse IDE 没有

标签 java eclipse eclipse-jdt ecj

我正在使用一个名为 iText 的库(使用 JAR 文件添加到项目中)。它的API可以在这里看到:https://coderanch.com/how-to/javadoc/itext-2.1.7/com/lowagie/text/Image.html

在我的项目中,我有一个简单的 Java 文件,名为 Worker.java,它使用此库:

import com.lowagie.text.Image;
public class Worker {
    public void createDetails() {
        Image img;
        try {
            img = Image.getInstance("...");
            float h = img.getHeight();
            float w = img.getWidth();
            ...
        } catch (Exception e) {...}
    }
}

在上面的代码中,使用 img.getHeight() 函数检索 Image 对象的高度。此函数是 com.lowagie.text.Rectangle 类的一部分,该类由 Image 类扩展。

在 Eclipse 中编译此代码时,IDE 很快识别出该函数来自 Rectangle 类,并且编译时没有任何错误。

但是,如果我使用独立的 ecj-4.4.jar文件以使用批处理编译器 (BatchCompiler.compile(...)) 编译项目,编译器报告以下错误:

1. ERROR in C:\...\Worker.java (at line 7)
        float h = img.getHeight();
                      ^^^^^^^^^
The method getHeight() is undefined for the type Image
----------

我只是不明白为什么会抛出这个错误。如果这是一个真正的错误,那么为什么 Eclipse 不报告它呢?

编辑:类路径中有此 JAR 的两个版本,这就是似乎出现错误的原因。不幸的是,由于这是一个多人参与的大型项目,因此我无法从项目中删除重复的 JAR。但是,Eclipse IDE 在查找该方法的正确 JAR 时似乎没有任何问题,那么为什么编译器会出现此问题呢?

最佳答案

虽然 Eclipse 从相应的项目中获取类路径设置,但批处理编译器却不会。您必须将库包含到类路径中。

参见the batch compiler's documentation here并查看 -cp 选项。您应该在其中包含相应的库。

编辑:在两个类路径中拥有相同的 jar 是不够的。您还必须考虑订单。

关于java - Eclipse JDT 编译器说方法未定义,但 Eclipse IDE 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090410/

相关文章:

java - Powermock 模拟类的内部 @Autowired 依赖项

Java 泛型 : override method that differs in parameterized return type

mysql - 添加 C mysql 库 Eclipse CDT 后 Makefile 出错

java - 为 ListView 设置背景

java - 如何使用 ASTRewrite 插入代码片段插入方法体?

java - 从插件修改 Eclipse UI

java - 大规模 Eclipse AST Java 重构

java - Spring Security - antMatcher 的 POST 方法(不是 antMatchers)

Java常见的Try/Finally block 围绕不同的代码块 - 代码风格

android - Poco C++ for Android 链接问题