实现效果1:

实现效果2:

代码:

类1:

package astTest;import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;import refactoring.test.test004;public class MainDo {public MainDo(String path) throws FileNotFoundException, IOException {CompilationUnit comp = getCompilationUnit(path);// DemoVisitor visitor = new DemoVisitor();// comp.accept(visitor);IfTransformer IfTransformer = new IfTransformer();comp.accept(IfTransformer);InstanceOfRefactor instanceOfRefactor = new InstanceOfRefactor();comp.accept(instanceOfRefactor); test004.saveFile(comp.toString(), path);}public static void main(String[] args) throws FileNotFoundException, IOException {System.out.println("begin");MainDo DemoVisitorTest = new MainDo("D:\\refactoringTest\\src\\astTest\\ChangeDemo01.java");MainDo DemoVisitorTest2 = new MainDo("D:\\refactoringTest\\src\\astTest\\ChangeDemo02.java");System.out.println("end");}/*** get compilation unit of source code* * @param javaFilePath* @return CompilationUnit*/public static CompilationUnit getCompilationUnit(String javaFilePath) {byte[] input = null;try {BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(javaFilePath));input = new byte[bufferedInputStream.available()];bufferedInputStream.read(input);bufferedInputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}ASTParser astParser = ASTParser.newParser(AST.JLS8);astParser.setSource(new String(input).toCharArray());astParser.setKind(ASTParser.K_COMPILATION_UNIT);CompilationUnit result = (CompilationUnit) (astParser.createAST(null));return result;}}

类2:

package astTest;
import java.util.ArrayList;
import java.util.List;import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.InfixExpression;
import org.eclipse.jdt.core.dom.InfixExpression.Operator;import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.StringLiteral;public class IfTransformer extends ASTVisitor {List<ASTNode> functionPartUpper=new ArrayList<>();List<ASTNode> upper=new ArrayList<>();List<ASTNode> center=new ArrayList<>();List<ASTNode> tail=new ArrayList<>();List<ASTNode> functionPartTail=new ArrayList<>();Expression  childExression=null;Expression  parentExression=null;@Overridepublic boolean visit(IfStatement node) {{Statement then=node.getThenStatement();Block block=(Block)then;List<Statement> child=block.statements();System.out.println(child);boolean isTail=false;//提取if内的内容,按照前中后组合isTail = getStatementsToList(node, child, isTail);//判断是否符合重构条件if (childExression==null) {return false;}//[modify by changxiaosong for 保存父类的上下部分的内容,防止被覆盖 at 2021年11月24日 beginBlock funcBlock = saveIfUpperAndTail(node,functionPartUpper,functionPartTail);//modify   by changxiaosong  at 2021年11月24日 end]//拼接代码块,放入if中//上面ifIfStatement blockNewIfUpper = gatherUpperIf(node);/*Block blockNew = node.getAST().newBlock();blockNew.statements().add((Statement)ASTNode.copySubtree(node.getAST(),  upper.get(0)));node.setThenStatement(blockNew);*///中间ifIfStatement blockNewIfCenter = gatherCenterIf(node);//下面ifIfStatement blockNewIfLow = gatherTailIf(node);//拼接上中下gatherAllNewStatements(node, funcBlock, blockNewIfUpper, blockNewIfCenter, blockNewIfLow);childExression=null;}return false;}public IfStatement gatherTailIf(IfStatement node) {IfStatement blockNewIfLow = node.getAST().newIfStatement();blockNewIfLow.setExpression((Expression)copyBlock(node,parentExression));Block blockTail= arrayToBlock(node,tail);blockNewIfLow.setThenStatement(blockTail);return blockNewIfLow;}public IfStatement gatherCenterIf(IfStatement node) {IfStatement blockNewIfCenter = node.getAST().newIfStatement();//拼接条件InfixExpression expression = node.getAST().newInfixExpression();expression.setLeftOperand((Expression)ASTNode.copySubtree(node.getAST(),  node.getExpression()));expression.setOperator(Operator.CONDITIONAL_AND);expression.setRightOperand((Expression)copyBlock(node,childExression));blockNewIfCenter.setExpression((Expression)copyBlock(node,expression));Block blockNewCenter = arrayToBlock(node,center);blockNewIfCenter.setThenStatement(blockNewCenter);return blockNewIfCenter;}public IfStatement gatherUpperIf(IfStatement node) {IfStatement blockNewIfUpper = node.getAST().newIfStatement();blockNewIfUpper.setExpression((Expression)ASTNode.copySubtree(node.getAST(),  parentExression));Block blockNewUpper = arrayToBlock(node,upper);blockNewIfUpper.setThenStatement(blockNewUpper);return blockNewIfUpper;}public void gatherAllNewStatements(IfStatement node, Block funcBlock, IfStatement blockNewIfUpper,IfStatement blockNewIfCenter, IfStatement blockNewIfLow) {funcBlock.statements().clear();//原来的头arrayAddToStatements(node,functionPartUpper,funcBlock.statements());//拆分的三个if条件funcBlock.statements().add(blockNewIfUpper);funcBlock.statements().add(blockNewIfCenter);funcBlock.statements().add(blockNewIfLow);//原来的尾巴 arrayAddToStatements(node,functionPartTail,funcBlock.statements());}public boolean getStatementsToList(IfStatement node, List<Statement> child, boolean isTail) {for (Statement object : child) {if (object instanceof IfStatement) {IfStatement childIf=(IfStatement)object;Statement childIfStatement=childIf.getThenStatement();parentExression=node.getExpression();childExression=childIf.getExpression();center.add(childIfStatement);isTail=true;}else {if (isTail) {tail.add(object);}else {upper.add(object);}}}return isTail;}public Block saveIfUpperAndTail(IfStatement node,List<ASTNode> functionPartUpper,List<ASTNode> functionPartTail) {return Tool.saveIfUpperAndTail(node, functionPartUpper, functionPartTail);}public ASTNode copyBlock(IfStatement node,Expression childExression) {return Tool.copyBlock(node, childExression);}public ASTNode copyBlock(IfStatement node, Statement sentenceOne) {return Tool.copyBlock(node, childExression);}public Block arrayToBlock(IfStatement node,List<ASTNode> upper) {Block blockNewUpper = node.getAST().newBlock();for (ASTNode nodeTmp : upper) {blockNewUpper.statements().add((Statement)ASTNode.copySubtree(node.getAST(),  nodeTmp));}return blockNewUpper;}public void arrayAddToStatements(IfStatement node,List<ASTNode> upper,List  statements) {Tool.arrayAddToStatements(node, upper, statements);}public boolean visitOrg(IfStatement node) {/*** fragment != null*/InfixExpression ie = (InfixExpression)node.getExpression();ie.setOperator(Operator.NOT_EQUALS);{Statement then=node.getThenStatement();Block block=(Block)then;List child=block.statements();}/*** if (fragment == null) {*     System.out.println("Wrong!");* }* else {*    System.out.println("Wrong!");* }*/node.setElseStatement((Block) ASTNode.copySubtree(node.getAST(),  node.getThenStatement()));/*** if (fragment == null) {*      System.out.println("Done!");* }* else {*    System.out.println("Wrong!");* }*/AST ast = node.getAST();MethodInvocation methodInv = ast.newMethodInvocation();SimpleName nameSystem = ast.newSimpleName("System");SimpleName nameOut = ast.newSimpleName("out");SimpleName namePrintln = ast.newSimpleName("println");//连接‘System’和‘out’//System.outQualifiedName nameSystemOut = ast.newQualifiedName(nameSystem, nameOut);//连接‘System.out’和‘println’到MethodInvocation节点//System.out.println()methodInv.setExpression(nameSystemOut);methodInv.setName(namePrintln);//"Done!"StringLiteral sDone = ast.newStringLiteral();sDone.setEscapedValue("\"Done!\"");//System.out.println("Done!")methodInv.arguments().add(sDone);//将方法调用节点MethodInvocation连接为表达式语句ExpressionStatement的子节点//System.out.println("Done!");ExpressionStatement es = ast.newExpressionStatement(methodInv);//将表达式语句连接为新建语句块节点Block的子节点//{//System.out.println("Done!");//}Block block = ast.newBlock();block.statements().add(es);MethodInvocation methodInv2 = ast.newMethodInvocation();SimpleName nameSystem2 = ast.newSimpleName("System");SimpleName nameOut2 = ast.newSimpleName("out");SimpleName namePrintln2 = ast.newSimpleName("println");QualifiedName nameSystemOut2 = ast.newQualifiedName(nameSystem2, nameOut2);methodInv2.setExpression(nameSystemOut2);methodInv2.setName(namePrintln2);StringLiteral sDone2 = ast.newStringLiteral();sDone2.setEscapedValue("\"Done!\"");methodInv2.arguments().add(sDone2);ExpressionStatement es2 = ast.newExpressionStatement(methodInv2);block.statements().add(es2);//将语句块节点Block连接为IfStatement节点的子节点node.setThenStatement(block);return false;}
}

类3:

package astTest;import java.util.ArrayList;
import java.util.List;import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.InstanceofExpression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;public class InstanceOfRefactor extends ASTVisitor{List bodyDeclarations=null;@Overridepublic boolean visit(IfStatement node) {// TODO Auto-generated method stubSimpleType childTpye=null;Expression child=null;Block ifBolck=null;Block elseBolck=null;//判断是否符合重构条件 if,else,instanceof if (node.getExpression() instanceof InstanceofExpression&&!(node.getElseStatement() instanceof IfStatement)) {InstanceofExpression  expression= (InstanceofExpression) node.getExpression();//提取条件中的对象,获取父类child=expression.getLeftOperand();childTpye=(SimpleType) expression.getRightOperand();//提取if体ifBolck=(Block)(node.getThenStatement());//提取else体elseBolck=(Block)(node.getElseStatement());}else {return false;}AST ast=node.getAST();//构建if方法块buildIfBlock(node, childTpye, child, ifBolck);//构建else方法块buildElseBlock(node, childTpye, child, elseBolck);//保存if块前后的内容List<ASTNode> functionPartUpper=new ArrayList<>();List<ASTNode> functionPartTail=new ArrayList<>();Tool.saveIfUpperAndTail(node, functionPartUpper, functionPartTail);//构建if上级内的其他内容changeMethordUsed(node, ast, functionPartUpper, functionPartTail);return false;}public void changeMethordUsed(IfStatement node, AST ast, List<ASTNode> functionPartUpper,List<ASTNode> functionPartTail) {//原来的头Block funcBlock=((Block)node.getParent());funcBlock.statements().clear();Tool.arrayAddToStatements(node,functionPartUpper,funcBlock.statements());MethodInvocation newMethord=ast.newMethodInvocation();newMethord.setName(ast.newSimpleName("fun01"));newMethord.arguments().add(ast.newSimpleName("customer"));ExpressionStatement es2 = ast.newExpressionStatement(newMethord);funcBlock.statements().add(es2);//原来的尾Tool.arrayAddToStatements(node,functionPartTail,funcBlock.statements());//保存文件}public void buildIfBlock(IfStatement node, SimpleType childTpye, Expression child, Block ifBolck) {ASTNode astNode=node.getParent().getParent().getParent();AST ast=node.getParent().getParent().getParent().getAST();MethodDeclaration ifFun= astNode.getAST().newMethodDeclaration();ifFun.setName(astNode.getAST().newSimpleName("fun01"));ifFun.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));SingleVariableDeclaration param=ast.newSingleVariableDeclaration();param.setType((Type) Tool.copyBlock(node, childTpye));param.setName(astNode.getAST().newSimpleName(child.toString()));ifFun.parameters().add(param);ifFun.setBody((Block)Tool.copyBlock(node, ifBolck));bodyDeclarations.add(ifFun);}public void buildElseBlock(IfStatement node, SimpleType childTpye, Expression child, Block elseBolck) {ASTNode astNode=node.getParent().getParent().getParent();AST ast=node.getParent().getParent().getParent().getAST();MethodDeclaration ifFun= astNode.getAST().newMethodDeclaration();ifFun.setName(astNode.getAST().newSimpleName("fun01"));ifFun.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));SingleVariableDeclaration param=ast.newSingleVariableDeclaration();param.setType(astNode.getAST().newSimpleType(ast.newSimpleName( "User" )));param.setName(astNode.getAST().newSimpleName(child.toString()));ifFun.parameters().add(param);ifFun.setBody((Block)Tool.copyBlock(node, elseBolck));bodyDeclarations.add(ifFun);}@Overridepublic boolean visit(TypeDeclaration node) {bodyDeclarations= node.bodyDeclarations();System.out.println("Class:\t" + node.getName());return true;}
}

JDT操作AST重构if块相关推荐

  1. ORA-01578和ORA-26040--NOLOGGING操作引起的坏块-错误解释和解决方案(文档ID 1623284.1)...

    ORA-01578和ORA-26040--NOLOGGING操作引起的坏块-错误解释和解决方案(文档ID 1623284.1) (一)NOLOGGING操作引起的坏块(ORA-01578和ORA-26 ...

  2. Palabos用户手册翻译及学习(四)非本地操作的数据处理器和块之间的耦合

    非本地操作的数据处理器和块之间的耦合 Palabos用户文档 的第十六章 (#)前言 原始文档 Dynamics classes and data processors are the nuts an ...

  3. Python操作AST解JS混淆

    通过生成语法树(AST),可快速修改代码中的一些混淆处理,从而简化代码,便于后续分析. 本文通过Python来把JS转为AST并进行简单的操作,内容很简单. 比如我们下图中的JS代码,有sum和min ...

  4. 【译】在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本

    本篇文章是讲述使用iTextSharp这个开源组件的系列文章的第三篇,iTextSharp可以通过Asp.Net创建PDFs,就像HTML和ASP.Net为文本提供了多种容器一样,iTextSharp ...

  5. echarts中formatter修改鼠标悬浮事件信息操作、echarts地图块、散点区分触发点击事件 只触发散点问题详解

    这里写目录标题 1.实例 2.案例详解 1.实例 这次我拿echarts中 地图组合散点图的实例 !!!实现效果:滑到散点显示不同于地图块的信息 及 formatter 提示窗自定义!!! 这个显示项 ...

  6. 2017.7.4 ACM校内赛 Round 2

    这是一个向导 A - hdu 3652 B - bzoj 4152 C - bzoj 2429 D - bzoj 1087 E - bzoj 1566 F - bzoj 4043 G - bzoj 1 ...

  7. ast java_Java代码分析器(一): JDT入门

    这是一个关于抽象语法树(Abstract Syntax Tree, AST)的故事. 抽象语法树是对程序代码的结构化表示,是对代码进行词法分析.语法分析后得到的产物.编译器要用到它,很多生产力工具也要 ...

  8. 哪些操作会造成raid数据无法恢复?raid多块硬盘离线后切记不要做这些事情

    [服务器raid5磁盘阵列情况简介] 西藏某政府机构使用的一台MS SQL SERVER服务器,是由4块硬盘组成的raid5磁盘阵列,划分一个逻辑卷,单盘为73GSCSI硬盘,组建于一台IBM X22 ...

  9. matlab对像素邻域操作,matlab图像的邻域操作与块操作

    1.图像的滑动邻域操作. 邻域操作是指将每个输入的像素值以及其某个邻域的像素值结合处理而得到对应的输出像素值的过程.邻域通常形状规则.如2*2,2*3之类. 滑动邻域操作一次处理一个像素. 对于m*n ...

最新文章

  1. 嵌入式开发调试学习与思考
  2. 【MCtalk讨论】 短视频平台出路在何方?
  3. c语言中调整颜色的函数_C语言中的输入输出函数
  4. R语言观察日志(part20)--包的组件之R代码
  5. mysql中临时修改参数用什么关键字_postgresql 中的参数查看和修改方式
  6. c语言mergesort 参数,归并排序C语言兑现MergeSort
  7. leetcode112 路径总和
  8. httpServlet,java web后台服务
  9. 【操作系统】进程の易错点解答
  10. c语言中按字节运算,C语言中位运算的巧用
  11. Linux 如何打开pyo文件,Python的文件类型
  12. 从零开始封装windows10 1803 超详细图文分享 第二篇:母盘的定制与安装
  13. 加性高斯白噪声 AWGN
  14. linux fat get entry,操作系统--主引导程序控制权的转移
  15. 研发质量管理6大根基
  16. 华为云ManageOne北向对接之基本名词概念(一)
  17. 【Linux】Linux 下socket 编程
  18. 程序员怎么做项目管理?
  19. 职高计算机工作总结范文,职高学习工作总结范文2000字
  20. 暂停更新,请到http://www.52brt.com上关注最新文章

热门文章

  1. 未明学院:保姆级四大par面面经和准备方法
  2. 查询微信被谁投诉举报方法
  3. NGFW防火墙的ASPF实现原理
  4. 宏碁暗影骑士4安装不了Linux,宏碁暗影骑士4评测:在细节中不断改进前行!
  5. wordpress cookies 遇到预料外错误 阿里云虚拟机
  6. 世界上最简单的会计书(资产负债表)
  7. 年会特辑丨池龙:上海“一网通办”政务服务模式分享
  8. 利用计算机打开电视盒子,原来还可以把旧笔记本电脑当电视盒子用!
  9. Python 位操作符(Bitwise)
  10. mixamo骨骼_Mixamo——在线三维人物角色骨骼自动绑定,上千动作库直接生成人物动画...