
package org.apache.tools.ant.taskdefs.optional;

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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ExecuteJava {

    private Commandline javaCommand = null;

    public void setJavaCommand(Commandline javaCommand) {
        this.javaCommand = javaCommand;
    }

    public void execute() throws BuildException{
        final String classname = javaCommand.getExecutable();
        final Object[] argument = { javaCommand.getArguments() };
        final Class[] param = { argument[0].getClass() };
        try {
            final Class target = Class.forName(classname);
            final Method main = target.getMethod("main", param);
            main.invoke(null, argument);
        } catch (NullPointerException e) {
            throw new BuildException("Could not find main() method in " + classname);
        } catch (ClassNotFoundException e) {
            throw new BuildException("Could not find " + classname + ". Make sure you have it in your classpath");
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (!(t instanceof SecurityException)) {
                throw new BuildException(t.toString());
            }
            // else ignore because the security exception is thrown
            // if the invoked application tried to call System.exit()
        } catch (Exception e) {
            throw new BuildException(e.toString());
        }
   }
}