现在我们的需求是对java代码进行转换:

转换前的java方法是:

    public XYDataItem addOrUpdate(Number x, Number y) {if (x == null) {throw new IllegalArgumentException("Null 'x' argument.");}XYDataItem overwritten = null;int index = indexOf(x);if (index >= 0 && !this.allowDuplicateXValues) {XYDataItem existing = (XYDataItem) this.data.get(index);try {overwritten = (XYDataItem) existing.clone();} catch (CloneNotSupportedException e) {throw new SeriesException("Couldn't clone XYDataItem!");}existing.setY(y);} else {if (this.autoSort) {this.data.add(-index - 1, new XYDataItem(x, y));} else {this.data.add(new XYDataItem(x, y));}if (getItemCount() > this.maximumItemCount) {this.data.remove(0);}}fireSeriesChanged();return overwritten;}

要求转换后的是:

public XYDataItem addOrUpdate(Number x, Number y) {if (x != null) {throw new IllegalArgumentException("Null 'x' argument.");}XYDataItem overwritten = null;int index = indexOf(x);if ((index <= 0) || (!this.allowDuplicateXValues)) {XYDataItem existing = ((XYDataItem) (this.data.get(index)));try {overwritten = ((XYDataItem) (existing.clone()));} catch (CloneNotSupportedException e) {throw new SeriesException("Couldn't clone XYDataItem!");}existing.setY(y);} else {if (this.autoSort) {this.data.add((-index) - 1, new XYDataItem(x, y));} else {this.data.add(new XYDataItem(x, y));}if (getItemCount() < this.maximumItemCount) {this.data.remove(0);}}fireSeriesChanged();return overwritten;
}

可以对比看到, 一些if里面的判断条件变了, 取反了.

spoon是用于分析、重写、转换、传输java源代码, 非常的强大....

下面是我们的代码,

1.设定依赖

<dependencies><dependency><groupId>fr.inria.gforge.spoon</groupId><artifactId>spoon-core</artifactId><version>8.3.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.6.2</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.6.2</version></dependency></dependencies>

2.写核心的转换方法:

package com.onyx;import spoon.Launcher;
import spoon.reflect.code.BinaryOperatorKind;
import spoon.reflect.code.CtBlock;
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.support.reflect.code.CtBinaryOperatorImpl;
import spoon.support.reflect.code.CtBlockImpl;
import spoon.support.reflect.code.CtIfImpl;
import spoon.support.reflect.declaration.CtMethodImpl;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;import static spoon.reflect.code.BinaryOperatorKind.*;public class JavaCodeTransform {/*** get origin and target method string** @return* @throws Exception*/public static Map<String, String> getOriginAndTargetMethod(String path) throws Exception {CtClass ctClass = Launcher.parseClass(getJavaCode(path));//get all methodSet<CtMethodImpl> allMethods = ctClass.getAllMethods();Map<String, String> map = new HashMap<String, String>(2);//scan all methodfor (CtMethodImpl method : allMethods) {String simpleName = method.getSimpleName();//only handle addOrUpdate methodif (!"addOrUpdate".equals(simpleName)) {continue;}//map.put("origin", method.toString());System.out.println("the origin  method is :" + method.toString());//get this  method body contentCtBlock body = method.getBody();List<CtStatement> statements = body.getStatements();for (CtStatement statement : statements) {if (!(statement instanceof CtIfImpl)) {continue;}CtIfImpl ctIf = (CtIfImpl) statement;CtBinaryOperatorImpl<Boolean> condition = (CtBinaryOperatorImpl) ctIf.getCondition();CtExpression<?> handOperand = condition.getLeftHandOperand();if (handOperand instanceof CtBinaryOperatorImpl) {CtBinaryOperatorImpl<Boolean> leftHandOperand = (CtBinaryOperatorImpl<Boolean>) handOperand;BinaryOperatorKind symbol = getOppositeSymbol(leftHandOperand.getKind());leftHandOperand.setKind(symbol);}//else conditionCtBlockImpl elseStatement = ctIf.getElseStatement();if (elseStatement != null) {List<CtIfImpl> ctIfs = elseStatement.getStatements();if (ctIfs != null && ctIfs.size() > 0) {for (CtIfImpl anIf : ctIfs) {replaceCondition(anIf);}}}replaceCondition(ctIf);}map.put("target", method.toString());System.out.println("the target method is :" + method.toString());}return map;}/*** reserve the if condition*/private static void replaceCondition(CtIfImpl ctIf) {if (ctIf == null) {return;}CtExpression<Boolean> ifCondition = ctIf.getCondition();if (ifCondition instanceof CtBinaryOperatorImpl) {CtBinaryOperatorImpl<Boolean> binaryOperator = (CtBinaryOperatorImpl<Boolean>) ifCondition;BinaryOperatorKind kind = binaryOperator.getKind();BinaryOperatorKind symbol = getOppositeSymbol(kind);binaryOperator.setKind(symbol);ctIf.setCondition(binaryOperator);}}/*** get the operator kind** @param kind* @return*/private static BinaryOperatorKind getOppositeSymbol(BinaryOperatorKind kind) {if (kind == null) {return null;}switch (kind) {case OR:return AND;case AND:return OR;case BITOR:return BITAND;case BITAND:return BITOR;case EQ:return NE;case NE:return EQ;case LT:return GT;case GT:return LT;case LE:return GE;case GE:return LE;}return null;}/*** get java method code string, into Demo class.** @return*/private static String getJavaCode(String path) throws IOException {File file = new File(path);BufferedReader reader = new BufferedReader(new FileReader(file));StringBuffer sb = new StringBuffer();sb.append("public class Demo { ");String tmp = null;while ((tmp = reader.readLine()) != null) {sb.append(tmp);}sb.append(" }");return sb.toString();}}

3. 写测试方法

import com.onyx.JavaCodeTransform;
import org.junit.Assert;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;public class Test {@org.junit.Testpublic void test() throws Exception {//put your source method file, i put D:\method.txtMap<String, String> map = JavaCodeTransform.getOriginAndTargetMethod("D:\\method.txt");String target = deleteAllBlank(map.get("target"));//load your result method in file, i put D:\result.txtString javaCode = deleteAllBlank(getJavaCode("D:\\result.txt"));Assert.assertEquals(true, target.equals(javaCode));}/*** delete all blocks** @param s* @return*/public String deleteAllBlank(String s) {if (s == null) {return s;}String replaceAll = s.replaceAll("\\s*", "");return replaceAll;}/*** get file content to string*/private String getJavaCode(String path) throws IOException {BufferedReader reader = new BufferedReader(new FileReader(new File(path)));StringBuffer sb = new StringBuffer();String tmp = null;while ((tmp = reader.readLine()) != null) {sb.append(tmp);}return sb.toString();}}

就完成了.

使用spoon对java代码进行转换相关推荐

  1. java 代码名称转换_计算机编码基础知识及Java中编码转换

    1.ASCII 码 学过计算机的人都知道 ASCII 码,ASCII 码是美国标准信息交换代码(American Standard Code for Information Interchange)的 ...

  2. 如何以及为什么使用Spoon分析,生成和转换Java代码

    Spoon是分析,生成和转换Java代码的工具. 在本文中,我们将看到通过使用以编程方式处理代码的技术可以实现什么. 我认为这些技术不是很广为人知或使用,这很遗憾,因为它们可能非常有用. 谁知道,即使 ...

  3. spoon java_如何以及为什么使用Spoon分析,生成和转换Java代码

    spoon java Spoon是分析,生成和转换Java代码的工具. 在本文中,我们将看到通过使用以编程方式处理代码的技术可以实现什么. 我认为这些技术不是很为人所知或使用,这很遗憾,因为它们可能非 ...

  4. 100转换成二进制 java,一段简单的java代码,十进制转二进制

    一段简单的java代码,十进制转二进制 mip版  关注:188  答案:5  悬赏:40 解决时间 2021-01-23 23:14 已解决 2021-01-23 05:43 代码如下,希望可以帮我 ...

  5. java代码转置sql数据_SQL Server中的数据科学:数据分析和转换–使用SQL透视和转置

    java代码转置sql数据 In data science, understanding and preparing data is critical, such as the use of the ...

  6. c语言将图像转换成字符画,25行Java代码将普通图片转换为字符画图片和文本的实现...

    本文主要介绍了25行Java代码将普通图片转换为字符画图片和文本的实现,分享给大家,具体如下: 原图 生成字符画文本(像素转换字符显示后,打开字符画显示相当于原图的好几倍大,不要用记事本打开,建议用n ...

  7. java flv转mp3_如何使用java代码进行视频格式的转换(FLV)

    一,前言 在给网页添加视频播放功能后,发现上传的视频有各种格式,那么就需要将他么转换成FLV,以很好的支持在线视频播放. 二,准备 drv43260.dll,ffmpeg.exe,mencoder.e ...

  8. java unix时间戳转换_unix时间戳的转换 Java实现【附代码】

    今天爱分享给大家带来unix时间戳的转换 Java实现[附代码],希望能够帮助到大家. Java时间转换成unix时间戳的方法 Java进行时间转换成unix timestamp的具体代码,供大家参考 ...

  9. 把AdobeIllustrator导出的SVG矢量图,自动转换成java代码或BufferedImage对象,这种需求多吗?

    Adobe Illustrator画的矢量图可以在任何像素下清晰显示图片,可以适配任何像素的显示器,自动识别图片内容然后转换成java代码的图片类,这种需求多吗?也可以自动读取矢量图,转换成Buffe ...

  10. java代码二进制转为十六进制_Java 中二进制转换成十六进制的两种实现方法

    Java 中二进制转换成十六进制的两种实现方法 每个字节转成16进制,方法1 /** * 每个字节转成16进制,方法1 * * @param result */ private static Stri ...

最新文章

  1. 5大典型模型测试单机训练速度超对标框架,飞桨如何做到?
  2. 一个PHP的HTTP POST方法
  3. 【学习小记】一般图最大匹配——带花树算法
  4. 实体词典 情感词典_基于词典的情感分析——简单实例
  5. 手机的余存电量还有多少的时候适合充电?
  6. cnn输入层_基于 CNN 的文本分类算法
  7. 《你的灯亮着吗》开始解决问题前,得先知道“真问题”是什么
  8. 基于python的大米粒分割(本文适合两个凹点的粘连物体)
  9. 中国移动宽带密码重置方法
  10. 自制java虚拟机_《深入理解Android:Java虚拟机ART》 —1.2.3 准备模拟器和自制系统镜像...
  11. 台式计算机能不能安装蓝牙驱动,台式电脑没有蓝牙该怎么安装?安装台式电脑的蓝牙的方法...
  12. 商业落地的 DeFi 热潮中,公链们或殊途而同归
  13. 20154312 曾林 Exp3 免杀原理与实践
  14. 1、计算机毕业设计论文分析-班主任管理系统
  15. canvas线性渐变实现:根据渐变线角度计算坐标x0,y0,x1,y1
  16. 通过ScheduledExecutorService代替Timer
  17. 信创操作系统--麒麟Kylin桌面版 (项目七 网络连接:有线、无线网络)
  18. d313(d3131)
  19. java -- cropper裁剪图片并base64上传 移动端简单示例
  20. 今日北方大部进入降水间歇期 南方仍多低温阴雨雪天气

热门文章

  1. 牛刀:中国未来房价基本走势…
  2. java jive歌词翻译_Java Jive歌词 Java JiveLrc歌词
  3. sin的傅里叶变换公式_正弦信号傅里叶变换
  4. 00900网页设计与制作多选题
  5. 展开操作符:一家人就这么被拆散了
  6. Matlab学习手记——输出到MathType公式编辑器
  7. 为什么 你会如此痛苦……?
  8. github下载release连接失败解决方法 亲测有效
  9. js柯里化的认识(本文转载自https://www.zhangxinxu.com/wordpress/2013/02/js-currying),觉得很有用就记下了
  10. 数字信号处理基础----正交基与正交函数集