从 Ant 访问 Java 类公共成员变量并在构建任务中使用它

发布于 2024-07-25 12:34:32 字数 529 浏览 2 评论 0原文

我的 Java 应用程序在几个地方显示其版本号,因此我将其作为公共最终变量存储在应用程序的主类中。 有什么方法可以在我的 Ant 构建任务中访问它吗? 本着自动化构建过程的精神,我希望 Ant 自动使用当前版本号命名压缩的可分发文件,但我不确定如何操作。 我猜它看起来像......

<target name="createZip" depends="build">
    <zip destfile="../dist/MyApp_${MyApp.version}.zip">
        <fileset dir="../dist">
            <include name="**/MyApp"/>
        </fileset>
    </zip>
</target>

我只是不知道该用什么来代替${MyApp.version}。 我意识到我可以将其放入构建属性文件中,但是如果能够直接从我已经存储它的类文件中提取它会更方便。

My Java app displays its version number in a few places, so I store that as a public final variable in the app's main class. Is there any way to access that in my Ant build tasks? In the spirit of automating the build process, I'd like Ant to automatically name the zipped distributable with the current version number, but I'm not sure how. I'm guessing it would look something like...

<target name="createZip" depends="build">
    <zip destfile="../dist/MyApp_${MyApp.version}.zip">
        <fileset dir="../dist">
            <include name="**/MyApp"/>
        </fileset>
    </zip>
</target>

I'm just not sure what to put in the place of ${MyApp.version}. I realize I could put this in the build properties file, but it would be a lot more convenient to be able to pull it straight from the class file I'm already storing it in.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哆啦不做梦 2024-08-01 12:34:32

我认为没有任何内置的 Ant 任务可以满足您的要求。 但是,您可以利用 Ant 的可扩展性来推出自己的产品。

我已经编写了一个非常(我的意思是非常)肮脏的示例,您可以将其用作正确任务的跳板。

package q1015732;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
 * Custom ant task that binds a property name to a static member of a class file.
 * 
 * @author Montrose
 */
public class BindPropertyTask extends Task{
    private String _classFile = null;
    private String _fieldName = null;
    private String _propName = null;

    /**
     * Set the field name of the class.
     * 
     * @param fieldName
     */
    public void setFieldName(String fieldName){
        _fieldName = fieldName;
    }

    /**
     * The class file.
     * @param classFile
     */
    public void setClassFile(String classFile){
        _classFile = classFile;
    }

    /**
     * The property name to bind
     * @param propName
     */
    public void setProperty(String propName)
    {
        _propName = propName;
    }

    /**
     * Load the class file, and grab the value of the field.
     * 
     * Throws exceptions if classfile, fieldname, or property have not been set.
     * 
     * Throws more execeptions if classfile does not exist, the field does not exist, or the field is not static.
     */
    public void execute() throws BuildException{
        if(_classFile == null) throw new BuildException("ClassFile is a required attribute");
        if(_fieldName == null) throw new BuildException("FieldName is a required attribute");
        if(_propName == null)  throw new BuildException("Property is  required attribute");

        CustomLoader loader = new CustomLoader();
        Class toInspect = null;
        Field toBind = null;
        Object value = null;

        try {
            toInspect = loader.loadClass(new FileInputStream(_classFile));
        } catch (Exception e) {
            throw new BuildException("Couldn't load class ["+e.getMessage()+"], in ["+(new File(_classFile).getAbsolutePath())+"]");
        }

        try{
            toBind = toInspect.getField(_fieldName);
        }catch(NoSuchFieldException e){
            throw new BuildException("Couldn't find field, '"+_fieldName+"'");
        }

        //Let us bind to private/protected/package-private fields
        toBind.setAccessible(true);

        try{
            value = toBind.get(null);
        }catch(NullPointerException e){
            throw new BuildException("Field is not static");
        } catch (Exception e) {
            throw new BuildException("Unable to access field ["+e.getMessage()+"]");
        }

        if(value != null)
            this.getProject().setProperty(_propName, value.toString());
        else
            this.getProject().setProperty(_propName, null);
    }

    /**
     * Custom class loader, for loading a class directly from a file.
     * 
     * This is hacky and relies on deprecated methods, be wary.
     * 
     * @author Montrose
     */
    class CustomLoader extends ClassLoader{
        public CustomLoader(){
            super(ClassLoader.getSystemClassLoader());
        }

        /**
         * Warning, here be (deprecated) dragons.
         * @param in
         * @return
         * @throws Exception
         */
        @SuppressWarnings("deprecation")
        public Class loadClass(InputStream in) throws Exception{
            byte[] classData = loadData(in);
            return this.defineClass(classData, 0, classData.length);
        }

        private byte[] loadData(InputStream in) throws Exception{
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int i;


            while((i = in.read(buffer)) != -1){
                out.write(buffer, 0, i);
            }

            return out.toByteArray();
        }
    }
}

使用此任务的示例构建文件:

<project name="q1015732">

<target name="test">
<taskdef name="static_bind" classname="q1015732.BindPropertyTask" />

<static_bind fieldname="StringBind" classfile="C:\Users\Montrose\workspace\StackOverflow Questions\q1015732\test\DummyMain.class" property="string.value" />
<static_bind fieldname="IntBind"    classfile="C:\Users\Montrose\workspace\StackOverflow Questions\q1015732\test\DummyMain.class" property="int.value" />
<static_bind fieldname="DoubleBind" classfile="C:\Users\Montrose\workspace\StackOverflow Questions\q1015732\test\DummyMain.class" property="double.value" />

<echo message="StringBind: ${string.value}" />
<echo message="IntBind:    ${int.value}" />
<echo message="DoubleBind: ${double.value}" />

</target>

</project>

DummyMain.java:

package q1015732.test;

public class DummyMain {
    public static String StringBind = "I'm a String!";
    public static int    IntBind    = 1024;
    public static double DoubleBind = 3.14159;
}

使用 Ant 文件构建的结果:

测试:
[echo] StringBind:我是一个字符串!
[回声] IntBind:1024
[回声]双重绑定:3.14159
构建成功

此任务存在许多随机问题:它依赖于已弃用的方法,它使用文件而不是类名,并且错误报告还有一些不足之处。 但是,您应该了解解决您的问题的自定义任务所需的要点。

I don't think there are any built in Ant tasks that do what you want. However, you could roll your own, taking advantage of the extensible nature of Ant.

I've hacked up a really (and I do mean really) dirty example you can use as a spring board to a proper Task.

package q1015732;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
 * Custom ant task that binds a property name to a static member of a class file.
 * 
 * @author Montrose
 */
public class BindPropertyTask extends Task{
    private String _classFile = null;
    private String _fieldName = null;
    private String _propName = null;

    /**
     * Set the field name of the class.
     * 
     * @param fieldName
     */
    public void setFieldName(String fieldName){
        _fieldName = fieldName;
    }

    /**
     * The class file.
     * @param classFile
     */
    public void setClassFile(String classFile){
        _classFile = classFile;
    }

    /**
     * The property name to bind
     * @param propName
     */
    public void setProperty(String propName)
    {
        _propName = propName;
    }

    /**
     * Load the class file, and grab the value of the field.
     * 
     * Throws exceptions if classfile, fieldname, or property have not been set.
     * 
     * Throws more execeptions if classfile does not exist, the field does not exist, or the field is not static.
     */
    public void execute() throws BuildException{
        if(_classFile == null) throw new BuildException("ClassFile is a required attribute");
        if(_fieldName == null) throw new BuildException("FieldName is a required attribute");
        if(_propName == null)  throw new BuildException("Property is  required attribute");

        CustomLoader loader = new CustomLoader();
        Class toInspect = null;
        Field toBind = null;
        Object value = null;

        try {
            toInspect = loader.loadClass(new FileInputStream(_classFile));
        } catch (Exception e) {
            throw new BuildException("Couldn't load class ["+e.getMessage()+"], in ["+(new File(_classFile).getAbsolutePath())+"]");
        }

        try{
            toBind = toInspect.getField(_fieldName);
        }catch(NoSuchFieldException e){
            throw new BuildException("Couldn't find field, '"+_fieldName+"'");
        }

        //Let us bind to private/protected/package-private fields
        toBind.setAccessible(true);

        try{
            value = toBind.get(null);
        }catch(NullPointerException e){
            throw new BuildException("Field is not static");
        } catch (Exception e) {
            throw new BuildException("Unable to access field ["+e.getMessage()+"]");
        }

        if(value != null)
            this.getProject().setProperty(_propName, value.toString());
        else
            this.getProject().setProperty(_propName, null);
    }

    /**
     * Custom class loader, for loading a class directly from a file.
     * 
     * This is hacky and relies on deprecated methods, be wary.
     * 
     * @author Montrose
     */
    class CustomLoader extends ClassLoader{
        public CustomLoader(){
            super(ClassLoader.getSystemClassLoader());
        }

        /**
         * Warning, here be (deprecated) dragons.
         * @param in
         * @return
         * @throws Exception
         */
        @SuppressWarnings("deprecation")
        public Class loadClass(InputStream in) throws Exception{
            byte[] classData = loadData(in);
            return this.defineClass(classData, 0, classData.length);
        }

        private byte[] loadData(InputStream in) throws Exception{
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int i;


            while((i = in.read(buffer)) != -1){
                out.write(buffer, 0, i);
            }

            return out.toByteArray();
        }
    }
}

An example build file using this task:

<project name="q1015732">

<target name="test">
<taskdef name="static_bind" classname="q1015732.BindPropertyTask" />

<static_bind fieldname="StringBind" classfile="C:\Users\Montrose\workspace\StackOverflow Questions\q1015732\test\DummyMain.class" property="string.value" />
<static_bind fieldname="IntBind"    classfile="C:\Users\Montrose\workspace\StackOverflow Questions\q1015732\test\DummyMain.class" property="int.value" />
<static_bind fieldname="DoubleBind" classfile="C:\Users\Montrose\workspace\StackOverflow Questions\q1015732\test\DummyMain.class" property="double.value" />

<echo message="StringBind: ${string.value}" />
<echo message="IntBind:    ${int.value}" />
<echo message="DoubleBind: ${double.value}" />

</target>

</project>

DummyMain.java:

package q1015732.test;

public class DummyMain {
    public static String StringBind = "I'm a String!";
    public static int    IntBind    = 1024;
    public static double DoubleBind = 3.14159;
}

The result of a build using the Ant file:

test:
[echo] StringBind: I'm a String!
[echo] IntBind: 1024
[echo] DoubleBind: 3.14159
BUILD SUCCESSFUL

There are a number of random problems with this task: it relies on deprecated methods, it takes files instead of class names, and the error reporting leaves a bit to be desired. However, you should get the gist of what is needed for a custom task that solves your problem.

皇甫轩 2024-08-01 12:34:32

创建一个扩展默认任务的 自定义 ant 任务 怎么样?

扩展 org.apache.tools.ant.taskdefs.Zip 类并重写 setDestFile() 方法
这样它就可以获取 MyApp.version 属性并设置目标文件名以包含该信息。

另一个解决方案是使用 CVSSVN (可能是 GIT Mercurial也有这个功能)并巧妙地利用这个功能
就像拥有一个包含类似内容的属性文件(在 SVN 中):

myApp.revision=$Revision$

并在您的代码和构建脚本中引用该属性。

What about creating a custom ant task that extends the default ?

Extend the org.apache.tools.ant.taskdefs.Zip class and override the setDestFile() method
so that it gets the MyApp.version attribute and sets the destination file name to contain that information.

Another solution is to use the keyword substitution feature from CVS and SVN (perhaps GIT and Mercurial have this feature too) and make a clever use of this feature
like having a property file with something like this (in SVN):

myApp.revision=$Revision$

and refer that property througout your code and build scripts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文