gpt4 book ai didi

Java 代码编译但产生 IllegalAccessError

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:09 25 4
gpt4 key购买 nike

在下面的代码中,我给出了两个主要类 - TestWorks 和 TestCompilesButFails。我不确定我是否理解失败 - 似乎 Arrays.asList() 表达式被赋予类型“AbstractBaseClass 列表”,但为什么在这里给出引用包​​本地类的类型是正确的在另一个包里?

// failing test class
import somepackage.*;
import java.util.Arrays;

public class TestCompilesButFails {
public static void main(String [] args){
// fails here with java.lang.IllegalAccessError:
// tried to access class somepackage.AbstractBaseClass
// from class TestCompilesButFails
for (Object o : Arrays.asList(new ConcreteA(), new ConcreteB())) {
System.out.println(o);
}
}
}


// package-local abstract base class
package somepackage;

abstract class AbstractBaseClass {
public abstract void doSomething();
}

// next two classes - public extenders of abstract base class
package somepackage;

public class ConcreteA extends AbstractBaseClass {
public void doSomething(){
System.out.print("Look, ma!\n");
}
}

package somepackage;

public class ConcreteB extends AbstractBaseClass {
public void doSomething(){
System.out.print("No types!\n");
}
}

// working test
import somepackage.*;

public class TestWorks {
public static void main(String [] args){
new ConcreteA().doSomething();
new ConcreteB().doSomething();
}
}

最佳答案

因为类型推断算法specified在 Java 语言规范中没有考虑类型可见性:

A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection.

至于他们为什么这样定义它,我怀疑这是为了避免为了处理罕见的极端情况而使已经非常复杂的算法变得更加复杂。毕竟,他们还写道:

Note also that type inference does not affect soundness in any way. If the types inferred are nonsensical, the invocation will yield a type error. The type inference algorithm should be viewed as a heuristic, designed to perfdorm well in practice. If it fails to infer the desired result, explicit type paramneters may be used instead.

在你的情况下会是:

    for (Object o : Arrays.<Object>asList(new ConcreteA(), new ConcreteB())) { 
System.out.println(o);
}

关于Java 代码编译但产生 IllegalAccessError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8073259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com