我有一系列描述各种实体类型的 XML 文件。我想使用基于 mixin 的实现将这些 XML 文件转换为 Java 类(源代码,以便我可以检查它们是否编译)。
一个例子:
描述村民的 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<entity>
<id>1</id>
<gathers>
<rate>12</rate>
</gathers>
<moves>
<speed>4</speed>
</moves>
</entity>
应该成为以下类:
public class Villager implements Gathers, Moves {
private final Gathers gathers;
private final Moves moves;
int getId() {
return 1;
}
@Override
public int getSpeed() {
return this.moves.getSpeed();
}
@Override
public int getRate() {
return this.gathers.getRate();
}
public Villager() {
super();
this.moves = new MovesMixin(4);
this.gathers = new GathersMixin(12);
}
}
我希望以一种易于扩展以涵盖新属性的方式来做到这一点。
是否有现有的软件包/工具可以执行类似的操作?
<小时/>带有模板的更新示例:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="entity">
/*
* DO NOT MODIFY
* This is an automatically generated class.
*/
package xslt.entities;
import xslt.*;
public strictfp final class <xsl:value-of select="typeName"/> implements <xsl:apply-templates select="moves" mode="implement"/><xsl:apply-templates select="gathers" mode="implement"/><xsl:apply-templates select="shoots" mode="implement"/>Entity {
<xsl:apply-templates select="moves" mode="mixin"/>
<xsl:apply-templates select="gathers" mode="mixin"/>
<xsl:apply-templates select="shoots" mode="mixin"/>
public <xsl:value-of select="typeName"/>() {
super();
}
}
</xsl:template>
<xsl:template match="moves" mode="implement">Moves, </xsl:template>
<xsl:template match="gathers" mode="implement">Gathers, </xsl:template>
<xsl:template match="shoots" mode="implement">Shoots, </xsl:template>
<xsl:template match="moves" mode="mixin">
private final Moves moves = new MovesMixin(<xsl:value-of select="speed"/>);
@Override
public int getSpeed() {
return this.moves.getSpeed();
}
</xsl:template>
<xsl:template match="gathers" mode="mixin">
private final Gathers gathers = new GathersMixin(<xsl:value-of select="rate"/>);
@Override
public int getRate() {
return this.gathers.getRate();
}
</xsl:template>
<xsl:template match="shoots" mode="mixin">
private final Shoots shoots = new ShootsMixin(<xsl:value-of select="range"/>);
@Override
public int getRange() {
return this.shoots.getRange();
}
</xsl:template>
</xsl:transform>
最佳答案
看一下 AspectJ 的类型间声明,它基本上允许您将方面中定义的新成员(字段、方法、构造函数)添加到现有类型。
http://www.eclipse.org/aspectj/doc/next/progguide/language-interType.html
它不能理解您的 XML 描述符,但肯定是一种在 java 中实现 mixin 的方法,所以也许您可以利用它。
关于java - 使用 XML 中的 mixin 生成 Java 源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926123/