Search code examples
javaantbuildbuild-process

How to print the build target in Java?


Say we have a class PrintTarget with main() inside of it.

Can we build/compile such that , somehow we should be able to send the build-target-name inside of the main. and when the main() is called it will print the build-target name.

I dont want the target name WHILE building. we all know how to do that. I want the generated JAR to remember the target name. Say we created the jar printTarget.jar And executed the jar #>java printTarget.jar I want this invocation to print the target name.


Solution

  • To pass data from build time to run time you need to write the data into a file that is stored in the JAR, e.g.

    <jar destfile="printTarget.jar">
      <fileset dir="${classes.dir}" />
      <manifest>
        <attribute name="Main-Class" value="com.example.Main" />
      </manifest>
      <!-- This is just a way to create a zip entry from inline text in the build
           file without having to <echo> it to a real file on disk first -->
      <mappedresources>
        <mergemapper to="com/example/buildinfo.properties"/>
        <string encoding="ISO-8859-1"># this is a generated file, do not edit
          targetname=custom-build-1
        </string>
      </mappedresources>
    </jar>
    

    which you can then read in your main method

    package com.example;
    import java.io.*;
    import java.util.Properties;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        Properties buildInfo = new Properties();
        InputStream is = Main.class.getResourceAsStream("buildinfo.properties");
        try {
          buildInfo.load(is);
        } finally {
          is.close();
        }
    
        System.out.println("Build target was " +
           buildInfo.getProperty("targetname", "<unknown>"));
      }
    }
    

    This should print

    Build target was custom-build-1