使用 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
Point
is changed to bepublic
, and then only thePoint
class is recompiled, and then executed with the previously existing binary forTest
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 classTest
could not be recompiled using this newPoint
class unless print were changed to bepublic
.) (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/