Antlr4生成的java代码中访问者模式的混淆。
创始人
2024-11-08 06:30:20
0

使用Lambda表达式来减少访问者模式的代码混淆。

考虑以下Antlr4生成的代码:

public class MyVisitor extends SomeBaseVisitor {
  @Override
  public String visitSomeRule(SomeRuleContext ctx) {
    String result = "";
    // Some code here...
    return result;
  }

  @Override
  public String visitAnotherRule(AnotherRuleContext ctx) {
    String result = "";
    // Some code here...
    return result;
  }
}

使用Java 8中的Lambda表达式,可以将访问者模式的代码重写为:

public class MyVisitor extends SomeBaseVisitor {
  private Map, Function> visitors = new HashMap<>();

  public MyVisitor() {
    visitors.put(SomeRuleContext.class, this::visitSomeRule);
    visitors.put(AnotherRuleContext.class, this::visitAnotherRule);
  }

  @Override
  public String visit(ParserRuleContext ctx) {
    return visitors.get(ctx.getClass()).apply(ctx);
  }

  private String visitSomeRule(SomeRuleContext ctx) {
    String result = "";
    // Some code here...
    return result;
  }

  private String visitAnotherRule(AnotherRuleContext ctx) {
    String result = "";
    // Some code here...
    return result;
  }
}

此重构允许我们将访问者方法存储在Map中并根据上下文类动态调用它们,在代码量大大减少的情况下仍保持代码清晰易读。

相关内容

热门资讯

有挂透视!德普之星辅助工具如何... 有挂透视!德普之星辅助工具如何设置,微乐家乡游戏攻略,妙招教程(讲解有挂)-哔哩哔哩1、很好的工具软...
科普透视!智星菠萝透视!都是真... 科普透视!智星菠萝透视!都是真的是有辅助教程(有挂助手)-哔哩哔哩1、金币登录送、破产送、升级送、活...
科普透视!aapoker怎么提... 科普透视!aapoker怎么提高中牌率,微乐江苏小程序游戏破解器下载,策略教程(有挂教学)-哔哩哔哩...
普及透视!智星菠萝可以辅助吗!... 普及透视!智星菠萝可以辅助吗!果然是真的有辅助教程(有挂技术)-哔哩哔哩1、在智星菠萝可以辅助吗插件...
详情透视!wepoker的辅助... 详情透视!wepoker的辅助器,微乐小程序辅助器脚本,方式教程(有挂猫腻)-哔哩哔哩1、首先打开w...
详细透视!fishpoker透... 详细透视!fishpoker透视底牌!本来有辅助工具(确实有挂)-哔哩哔哩1、fishpoker透视...
专业透视!竞技联盟破解版最新版... 专业透视!竞技联盟破解版最新版,微信小程序微乐挂如何获取,法门教程(竟然有挂)-哔哩哔哩1、起透看视...
分享透视!约局吧能不能开挂!切... 分享透视!约局吧能不能开挂!切实真的有辅助攻略(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
分享透视!hhpoker是正规... 分享透视!hhpoker是正规的吗,微乐自建房辅助神器怎么安装,资料教程(的确有挂)-哔哩哔哩1、下...
教你透视!pokemmo内置修... 教你透视!pokemmo内置修改器!一贯是有辅助脚本(发现有挂)-哔哩哔哩1、pokemmo内置修改...