java - 使用 javac 而不是 Eclipse 编译泛型时出错

标签 java eclipse generics

我有一个类在内部多次调用它自己的方法之一。所有这些方法都采用通用参数(Guava 的 Predicate)。 Eclipse 对此进行了很好的编译,没有报告错误,也没有警告指示器,编译器设置为 Java 1.6 兼容性。 Gradle(使用 JDK 1.6.0_37)报告其中一次调用该方法时找不到该方法的符号,但其他时候可以。这好像涉及到Guava的Predicates#and()静态方法的使用。但是用 Guava 的 Predicates#not() 进行类似的调用是可行的。

我已将代码简化为以下内容:

import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;

public class MyClass {
    public List<String> doStuffAnd(List<String> l, Predicate<String> p1, Predicate<String> p2) {
        // eclipse fine, gradle complains it can't find symbol doStuff
        return doStuff(l, and(p1, p2));
    }

    public List<String>  doStuffNot(List<String> l, Predicate<String> p) {
        // both eclipse and gradle compile fine
        return doStuff(l, not(p));
    }

    public List<String> doStuff(List<String> l, Predicate<String> p) {
        return FluentIterable.from(l).filter(p).toList();
    }
}

产生的编译错误是:

doStuff(java.util.List,com.google.common.base.Predicate) in MyClass cannot be applied to (java.util.List,com.google.common.base.Predicate) return doStuff(l, and(p1, p2)); ^

如果我显式键入对 Predicates.and() 的调用,如下所示

return doStuff(l, Predicates.<String>and(p1, p2));

那就没问题了。但我不必通过调用 Predicates.not() 来执行此操作,如果我将 #and 表达式提取为局部变量,它也可以工作。

  1. 使用#and调用和使用#not调用有什么区别?
  2. 我能做些什么来避免这种情况,既不涉及键入 and 调用,也不涉及提取 and 表达式?
  3. 为什么 gradle 编译器和 Eclipse 编译器之间存在差异?

最佳答案

OP 的解决方案

  1. and之间的区别和 not是那个and将其参数的通用签名定义为 Predicate<? super T> ,而 not使用 Predicate<T> 的简单参数签名.
  2. 为了解决这个问题,我定义了doStuffAnd带参数:Predicate<? super String> .

关于java - 使用 javac 而不是 Eclipse 编译泛型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26023820/

相关文章:

java - 使用 JavaFX 制作 Eclipse 插件?

java - 如何对 mongodb 数组字段进行全文搜索?

c# - 获取通用列表项的计数

java - 截断/紧凑 PDF417 矩阵

java - try block 和 ArrayList 的问题 [Java]

java - 与 ignite 相关的构建问题

android - Android Design Support 库的 Eclipse 错误

java - java(eclipse)中的Cplex目标函数实现

ios - 如何在 Swift 中创建具有多个模型的通用数组?

c# - HtmlHelper<ChildType> 不可分配给 HtmlHelper<MotherType>