为了账号安全,请及时绑定邮箱和手机立即绑定

在lambda表达式中使用的变量应该是最终变量或有效的最终变量。

在lambda表达式中使用的变量应该是最终变量或有效的最终变量。

人到中年有点甜 2019-07-09 14:11:34
在lambda表达式中使用的变量应该是最终变量或有效的最终变量。在lambda表达式中使用的变量应该是最终变量或有效的最终变量。当我试图用calTz它显示了这个错误。private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {     try {        cal.getComponents().getComponents("VTIMEZONE").forEach(component->{         VTimeZone v = (VTimeZone) component;            v.getTimeZoneId();            if(calTz==null) {                calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());            }            });     } catch (Exception e) {         log.warn("Unable to determine ical timezone", e);     }     return null;}
查看完整描述

3 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

final变量意味着它只能被实例化一次。在Java中,您不能在lambda和匿名内部类中使用非最终变量。

您可以使用旧的for-each循环重构代码:

private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
    try {
        for(Component component : cal.getComponents().getComponents("VTIMEZONE")) {
        VTimeZone v = (VTimeZone) component;
           v.getTimeZoneId();
           if(calTz==null) {
               calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
           }
        }
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return null;}

即使我不明白这段代码的含义:

  • 你叫.

    v.getTimeZoneId();

    而不使用其返回值
  • 带着任务

    calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());

    您不会修改最初传递的

    calTz

    而且你没有在这个方法中使用它
  • 你总是回来

    null

    ,你为什么不

    void

    作为返回类型?

希望这些建议也能帮助你提高。


查看完整回答
反对 回复 2019-07-09
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

虽然其他答案证明了这一要求,但他们没有解释为什么这种要求是存在的。

JLS提到了为什么第15.27.2节:

对有效的最终变量的限制禁止访问动态变化的局部变量,这些局部变量的捕获可能会带来并发问题。

为了降低bug的风险,他们决定确保捕获的变量不会发生变异。


查看完整回答
反对 回复 2019-07-09
?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

从lambda中,您无法获得对任何不是最终结果的引用。您需要从Lamda外部声明一个最后的包装器来保存您的变量。

我添加了最后的“引用”对象作为这个包装器。

private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
    final AtomicReference<TimeZone> reference = new AtomicReference<>();

    try {
       cal.getComponents().getComponents("VTIMEZONE").forEach(component->{
        VTimeZone v = (VTimeZone) component;
           v.getTimeZoneId();
           if(reference.get()==null) {
               reference.set(TimeZone.getTimeZone(v.getTimeZoneId().getValue()));
           }
           });
    } catch (Exception e) {
        //log.warn("Unable to determine ical timezone", e);
    }
    return reference.get();}


查看完整回答
反对 回复 2019-07-09
  • 3 回答
  • 0 关注
  • 4915 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号