在Eclipse中生成java代码?

And*_*yuk 15 java eclipse android code-generation

有谁知道在eclipse中自动生成Java源代码的方法,例如xml或json文件?

我正在考虑做的一个很好的例子是Google Android sdk所做的事情:他们有一个从资源自动生成的R类.

每次在Eclipse中保存资源文件时,R类都会自动重新生成.

更新:示例:在文本(xml或json文件)中,我有以下内容:

 <tags>
     <tag id="ALPHA">
         <description>The first alpha tag.</description>
         <value>231232</value>
     </tag>
     <tag id="BETA">
         <description>This is the beta tag.</description>
         <value>231232</value>
     </tag>
Run Code Online (Sandbox Code Playgroud)

然后在我生成的java类中,说RI会有类似的东西:

R.tags.ids.ALPHA //refers to an enum value for example
R.tags.values.ALPHA //refers to final int with avlue 231232
R.tags.descriptions.ALPHA //refers to the String with description
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ada*_*ent 3

我根据您的评论添加另一个答案,也是因为我真的不建议在 Google Android Resource SDK 之外执行此操作。Google 基本上使用静态类(单例)的层次结构来存储其资源。您需要使 XSLT 生成静态成员变量而不是 getter 和 setter。

我基本上采用了我的旧答案并将其更改为所有成员变量的静态。 这样做必须非常小心,因为我见过很多错误使用“static”修饰符的错误。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:template match="/" priority="100">
    public class <xsl:value-of select="name(node())" /> {
        <xsl:apply-templates  select="child::node()" />
    }
    </xsl:template>
    <xsl:template match="/*/*">
        public static String <xsl:value-of select="name()" />;
        public static String get<xsl:value-of select="name()" /> {
            return <xsl:value-of select=" name()" />;
        }

        public void static set<xsl:value-of select="name()" />(String value) {
            <xsl:value-of select="name()" /> = value;
        }
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

如果您使用此示例 XML 进行处理:

<?xml version="1.0" encoding="UTF-8"?>
<Human>
    <EyeColor>brown</EyeColor>
    <HairColor>brown</HairColor>
</Human>
Run Code Online (Sandbox Code Playgroud)

你会得到类似的东西: public class Human {

    public static String EyeColor;

    public static String getEyeColor {
        return EyeColor;
    }

    public static void setEyeColor(String value) {
        this.EyeColor = value;
    }


    public static String HairColor;
    public static String getHairColor {
        return HairColor;
    }

    public static void setHairColor(String value) {
        this.HairColor = value;
    }


}
Run Code Online (Sandbox Code Playgroud)