使用泛型的Maven jar依赖问题

时间:2018-09-19 16:36:57

标签: java maven generics dependencies subclass

我有一个lib.jar,其中包含以下类:

库:

package lib;

public class Lib {
    public <T extends Test<T>> void test(T test) {

    }
}

测试:

package lib;

public class Test<SELF extends Test<SELF>> {

}

在我的Maven项目中,我已按路径将lib.jar添加为系统范围的依赖项。该项目包含以下类别:

TestSub:

package app;

import lib.Test;

public class TestSub extends Test<TestSub> {

}

TestSubSub:

package app;

public class TestSubSub extends TestSub {

}

和应用程序:

package app;

import lib.Lib;

public class App {
    public static void main(String[] args) {
        Lib lib = new Lib();
        lib.test(new TestSub()); // <-- This compiles
        lib.test(new TestSubSub()); // <-- This does not compile
        lib.test((TestSub) new TestSubSub()); // <-- This compiles
    }
}

您可以在App类的注释中看到,只有lib.test(new TestSub());lib.test((TestSub) new TestSubSub());会编译,而不会lib.test(new TestSubSub());。当我不使用maven并将lib.jar作为外部Jar添加到Eclipse Java项目中时,此代码就没有问题。

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project app: Compilation failure
[ERROR] <path to project>/src/main/java/app/App.java:[9,20] method test in class lib.Lib cannot be applied to given types;
[ERROR]   required: T
[ERROR]   found: app.TestSubSub
[ERROR]   reason: inferred type does not conform to upper bound(s)
[ERROR]     inferred: app.TestSubSub
[ERROR]     upper bound(s): lib.Test<app.TestSubSub>

这是怎么了?

0 个答案:

没有答案