Java: "attempting to assign weaker access privilege error"(使用 1.8 编译 JDK 1.6 源代码)

标签 java gradle java-8 java-6

使用 Gradle,我们尝试编译旧版 Java 代码,该代码是使用 JDK 1.8 编译器为 JDK 1.6 开发的。 在某些时候,编译过程会因错误而退出

attempting to assign weaker access privileges; was public

(错误的原因本身很明显:我们在抽象类中有一个方法,该方法被声明为 public,但实现类将其声明为 protected。 )

使用 JDK 1.6 进行编译,我们从未遇到过任何问题。 现在由于多种原因,我们必须使用 Java 8 编译代码,从而遇到了这个问题。

我们已经在构建时尝试过项目设置 -PsourceCompatibility=1.6 (还有 -PtargetCompatibility=1.8),但没有效果。

目前,重构整个产品代码(预计会出现更多类似的错误)是不可能的,因此我们正在寻找一种解决方案来使用新的 JDK 构建旧代码。

对此有什么帮助吗?

最佳答案

对您的系统过去使用 Java 1.6 的唯一解释是,父类(super class)中的方法访问已更改为 public,而无需重新编译子类。从一开始就禁止降低子类中的可访问性。

Java Language Specification 1.6在第 344 页提供了此解释:

if the package points defines the class Point:

package points;
public class Point {
    public int x, y;
    protected void print() {
        System.out.println("(" + x + "," + y + ")");
    }
}

used by the Test program:

class Test extends points.Point {
    protected void print() {
        System.out.println("Test");
    }
    public static void main(String[] args) {
        Test t = new Test();
        t.print();
    }
}

then these classes compile and Test executes to produce the output:

Test

If the method print in class Point is changed to be public, and then only the Point class is recompiled, and then executed with the previously existing binary for Test then no linkage error occurs, even though it is improper, at compile time, for a public method to be overridden by a protected method (as shown by the fact that the class Test could not be recompiled using this new Point class unless print were changed to be public.) (emphasis added)

如果您必须使用 Java 1.8 编译器重新创建确切的行为,请将父类(super class)中的可访问性更改为 protected,编译父类(super class)和子类,然后将父类(super class)中的可访问性更改回 public ,并且仅编译父类(super class)。但是,此时我强烈建议更改子类以提供适当的可访问性。

关于Java: "attempting to assign weaker access privilege error"(使用 1.8 编译 JDK 1.6 源代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125702/

相关文章:

java - 当我尝试在 Android 应用程序中使用 Javers 时,模块中的重复类错误

java - 以编程方式启动 Jetty 9

json - Jackson JSR-310 模块无法反序列化最简单的 OffsetDateTime 格式

java - Reader#lines() 由于其拆分器中不可配置的批量大小策略而严重并行化

java - 根据给定的纬度、经度和半径值在 Java 中查找最小和最大纬度和经度

java - Java 9 JPMS 是否有 JMS 模块?

android - 生命周期 Android 插件 gradle

java - 在 Java 8 中将整数数组转换为字符串数组的最简单方法

java - 将 Ant 项目转换为带有日期构建的 Gradle

gradle - 如何根据配置文件将文件复制到WAR中?