java.lang.error类属于,异常原因java.lang.VerifyError:操作数堆栈上的错误类型

The below simple java code sends the

java.lang.VerifyError: Bad type on operand stack exception

public class TestJavaCodes {

int parentData = 0;

public void init() {

A ob = new B();

}

public static void main(String[] args) {

TestJavaCodes testJavaCodes = new TestJavaCodes();

testJavaCodes.init();

}

public static class A {

public A(MyLambdaFunc lambdaFunc) {

}

}

public class B extends A {

public B() {

super((data1, type) -> {

parentData = 1;

});

}

}

@FunctionalInterface

public static interface MyLambdaFunc {

public void onData(String data, int type);

}

}

If I remove the code

parentData = 1

from B's constructor, the exception won't come.

Can any one tell the reason for this?

解决方案

The problem arises because your lambda expression does not reference this or a member of this but a member of the outer this. Had you written class B like

public class B extends A {

int innerData;

public B() {

super((data1, type) -> innerData = 1);

}

}

the compiler rejected it without any doubts as accessing innerData implies accessing this.

The point about the outer instance is that it is a constant which is even available when the inner instance has not been fully constructed yet. So it’s correct to accept the code but unfortunately the compiler generates code which attempts to access the outer instance via an implicit field of the inner class instance, thus the lambda expression requires an instance of the inner class and attempting to use the not fully constructed inner class instance produces the error.

It can be easily demonstrated that the code can be compiled correctly:

public class B extends A {

public B() {

this(TestJavaCodes.this);

}

private B(TestJavaCodes outer) {

super((data1, type) -> outer.parentData = 1);

}

}

with that small change, the lambda expression refers to the outer instance without accessing the inner instance and no error arises.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值