Example usage for java.lang.reflect Method invoke

List of usage examples for java.lang.reflect Method invoke

Introduction

In this page you can find the example usage for java.lang.reflect Method invoke.

Prototype

@CallerSensitive
@ForceInline 
@HotSpotIntrinsicCandidate
public Object invoke(Object obj, Object... args)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException 

Source Link

Document

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

Usage

From source file:InvokeMain.java

public static void main(String[] argv) {
    //+//from   w  ww. j ava2  s  . co  m
    try {
        // First, find the class.
        Class c = Class.forName("InvokeMain"); // RECURSION
        System.out.println(c);

        // Create the array of Argument Types
        Class[] argTypes = { argv.getClass(), // array is Object!
        };

        // Now find the method
        Method m = c.getMethod("main", argTypes);
        System.out.println(m);

        // Create the actual argument array
        Object passedArgv[] = { argv };

        // Now invoke the method.
        m.invoke(null, passedArgv);

    } catch (Exception e) {
        System.err.println(e);
    }
    //-
}

From source file:javarestart.JavaRestartLauncher.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <URL> {<MainClass>}");
        return;/*from w  ww  .  ja va  2s.  co  m*/
    }

    if (args[0].equals("fork")) {
        String[] args2 = new String[args.length - 1];
        for (int i = 0; i < args.length - 1; i++) {
            args2[i] = args[i + 1];
        }
        fork(args2);
        return;
    }

    AppClassloader loader = new AppClassloader(args[0]);
    Thread.currentThread().setContextClassLoader(loader);
    String main;
    JSONObject obj = getJSON(args[0]);
    if (args.length < 2) {
        main = (String) obj.get("main");
    } else {
        main = args[1];
    }

    String splash = (String) obj.get("splash");
    if (splash != null) {
        SplashScreen scr = SplashScreen.getSplashScreen();
        if (scr != null) {
            URL url = loader.getResource(splash);
            scr.setImageURL(url);
        }
    }

    //auto close splash after 45 seconds
    Thread splashClose = new Thread() {
        @Override
        public void run() {
            try {
                sleep(45000);
            } catch (InterruptedException e) {
            }
            SplashScreen scr = SplashScreen.getSplashScreen();
            if ((scr != null) && (scr.isVisible())) {
                scr.close();
            }
        }
    };
    splashClose.setDaemon(true);
    splashClose.start();

    Class mainClass = loader.loadClass(main);
    Method mainMethod = mainClass.getMethod("main", String[].class);
    mainMethod.setAccessible(true);
    mainMethod.invoke(null, new Object[] { new String[0] });
}

From source file:X.java

public static void main(String[] argv) {
    try {/*w w w.  j a va  2s.  c  o m*/
        Class clX = X.class; // or Class.forName("X");
        // To find a method we need the array of matching Class types.
        Class[] argTypes = { String.class };

        // Now find a Method object for the given method.
        Method worker = clX.getMethod("work", argTypes);

        // To INVOKE the method, we need its actual arguments, as an array.
        Object[] theData = { "Chocolate Chips" };

        // The obvious last step: invoke the method.
        worker.invoke(new X(), theData);
    } catch (Exception e) {
        System.err.println("Invoke() failed: " + e);
    }
}

From source file:ReflexiveInvocation.java

/**
 * Main demo method.//from  ww  w  .  j av  a  2s  . c o m
 * 
 * @param args
 *          the command line arguments
 * 
 * @throws RuntimeException
 *           __UNDOCUMENTED__
 */
public static void main(final String[] args) {
    try {
        final int CALL_AMOUNT = 1000000;
        final ReflexiveInvocation ri = new ReflexiveInvocation();
        int idx = 0;

        // Call the method without using reflection.
        long millis = System.currentTimeMillis();

        for (idx = 0; idx < CALL_AMOUNT; idx++) {
            ri.getValue();
        }

        System.out.println("Calling method " + CALL_AMOUNT + " times programatically took "
                + (System.currentTimeMillis() - millis) + " millis");

        // Call while looking up the method in each iteration.
        Method md = null;
        millis = System.currentTimeMillis();

        for (idx = 0; idx < CALL_AMOUNT; idx++) {
            md = ri.getClass().getMethod("getValue", null);
            md.invoke(ri, null);
        }

        System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with lookup took "
                + (System.currentTimeMillis() - millis) + " millis");

        // Call using a cache of the method.
        md = ri.getClass().getMethod("getValue", null);
        millis = System.currentTimeMillis();

        for (idx = 0; idx < CALL_AMOUNT; idx++) {
            md.invoke(ri, null);
        }

        System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with cache took "
                + (System.currentTimeMillis() - millis) + " millis");
    } catch (final NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    } catch (final InvocationTargetException ex) {
        throw new RuntimeException(ex);
    } catch (final IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:de.escidoc.core.admin.AdminMain.java

/**
 * Main Method, depends on args[0] which method is executed.
 * //from   w ww .j  a  va  2  s  . c o  m
 * @param args
 *            arguments given on commandline
 * @throws NoSuchMethodException
 *             e
 * @throws InvocationTargetException
 *             e
 * @throws IllegalAccessException
 *             e
 */
public static void main(final String[] args) {
    int result = 20;

    try {
        AdminMain admin = new AdminMain();

        // call has to have at least one argument
        if (args.length > 0 && !StringUtils.isEmpty(args[0])) {
            String methodToCall = methods.get(args[0]);

            if (!StringUtils.isEmpty(methodToCall)) {
                log.info("memory (free / max. available): " + Runtime.getRuntime().freeMemory() / 1024 / 1024
                        + " MB" + " / " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + " MB");

                Class<?>[] paramTypes = { String[].class };
                Method thisMethod = admin.getClass().getDeclaredMethod(methodToCall, paramTypes);

                thisMethod.invoke(admin, new Object[] { args });
                result = 0;
            } else {
                admin.failMessage("provided tool name: " + StringUtils.join(args, " "));
            }
        } else {
            admin.failMessage();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        e.printStackTrace();
    }
    System.exit(result);
}

From source file:LauncherBootstrap.java

/**
 * The main method.//from   w  ww.  j a  v  a2 s  . c  om
 *
 * @param args command line arguments
 */
public static void main(String[] args) {

    try {

        // Try to find the LAUNCHER_JAR_FILE_NAME file in the class
        // loader's and JVM's classpath.
        URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);
        if (coreURL == null)
            throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);

        // Coerce the coreURL's directory into a file
        File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile();

        // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same
        // directory as this class
        File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME);
        if (!propsFile.canRead())
            throw new FileNotFoundException(propsFile.getPath());

        // Load the properties in the LAUNCHER_PROPS_FILE_NAME 
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(propsFile);
        props.load(fis);
        fis.close();

        // Create a class loader that contains the Launcher, Ant, and
        // JAXP classes.
        URL[] antURLs = LauncherBootstrap
                .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME));
        URL[] urls = new URL[1 + antURLs.length];
        urls[0] = coreURL;
        for (int i = 0; i < antURLs.length; i++)
            urls[i + 1] = antURLs[i];
        ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
        URLClassLoader loader = null;
        if (parentLoader != null)
            loader = new URLClassLoader(urls, parentLoader);
        else
            loader = new URLClassLoader(urls);

        // Load the LAUNCHER_MAIN_CLASS_NAME class
        launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME);

        // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString()
        // method as we need it for printing the usage statement
        Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString",
                new Class[] { String.class });

        // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method.
        // If the ant.class.path property is not set correctly in the 
        // LAUNCHER_PROPS_FILE_NAME, this will throw an exception.
        Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class });
        int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue();
        // Always exit cleanly after invoking the start() method
        System.exit(returnValue);

    } catch (Throwable t) {

        t.printStackTrace();
        System.exit(1);

    }

}

From source file:de.andrena.tools.macker.plugin.CommandLineFile.java

public static void main(String[] args) throws Exception {
    if (args.length == 0 || args.length > 2) {
        System.err.println("Usage: CommandLineFile <main class> [command line arguments file]");
        System.exit(1);//w  ww  . ja  v a  2s . co m
    }

    String className = args[0];
    Class<?> clazz = Class.forName(className);
    Method main = clazz.getMethod("main", new Class[] { String[].class });

    List<String> lines = new ArrayList<String>();
    if (args.length == 2) {
        Reader in = new InputStreamReader(new FileInputStream(args[1]), "UTF-8");
        try {
            lines = IOUtils.readLines(in);
        } finally {
            in.close();
        }
    }

    try {
        main.invoke(null, new Object[] { lines.toArray(new String[lines.size()]) });
    } catch (InvocationTargetException ex) {
        Throwable cause = ex.getTargetException();
        if (cause instanceof Error) {
            throw (Error) cause;
        }
        throw (Exception) cause;
    }
}

From source file:com.pinterest.terrapin.tools.TerrapinAdmin.java

public static void main(String[] args) throws Exception {
    PropertiesConfiguration configuration = TerrapinUtil
            .readPropertiesExitOnFailure(System.getProperties().getProperty("terrapin.config"));
    TerrapinAdmin admin = new TerrapinAdmin(configuration);
    String action = args[0];/*from  w w  w  . j a v a2s  .  c o  m*/
    Method[] methods = admin.getClass().getMethods();
    boolean done = false;
    for (Method method : methods) {
        if (method.getName().equals(action) && !Modifier.isStatic(method.getModifiers())) {
            method.invoke(admin, (Object) args);
            done = true;
        }
    }
    if (!done) {
        LOG.error("Could not find a function call for " + args[0]);
        System.exit(1);
    }
}

From source file:com.nabla.project.application.tool.runner.ServiceRunner.java

/**
 * DOCUMENT ME!//ww  w  . jav a 2s. c  o m
 * 
 * @param args DOCUMENT ME!
 * @throws Exception DOCUMENT ME!
 * @throws RuntimeException DOCUMENT ME!
 */
public static void main(String args[]) throws Exception {

    ObjectInputStream ois = new ObjectInputStream(System.in);
    Object methodArgs[] = (Object[]) ois.readObject();

    if (args.length < 3) {

        throw new RuntimeException(
                "Error : usage : java com.nabla.project.application.tool.runner.ServiceRunner configFileName beanName methodName");

    }

    String configFileName = args[0];
    String beanName = args[1];
    String methodName = args[2];
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { configFileName });
    Object service = context.getBean(beanName);
    Method serviceMethod = null;
    Method methods[] = service.getClass().getMethods();

    for (Method method : methods) {

        if (method.getName().equals(methodName)) {

            serviceMethod = method;

        }

    }

    if (serviceMethod == null) {

        throw new RuntimeException("Method " + methodName + " not found in class " + service.getClass());

    }

    serviceMethod.invoke(service, methodArgs);

}

From source file:org.eclipse.swt.snippets.SnippetLauncher.java

public static void main(String[] args) {
    File sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR;
    boolean hasSource = sourceDir.exists();
    int count = 500;
    if (hasSource) {
        File[] files = sourceDir.listFiles();
        if (files.length > 0)
            count = files.length;//from   ww w . j  a v a2 s .c  o m
    }
    for (int i = 1; i < count; i++) {
        if (SnippetsConfig.isPrintingSnippet(i))
            continue; // avoid printing to printer
        String className = "Snippet" + i;
        Class<?> clazz = null;
        try {
            clazz = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + className);
        } catch (ClassNotFoundException e) {
        }
        if (clazz != null) {
            System.out.println("\n" + clazz.getName());
            if (hasSource) {
                File sourceFile = new File(sourceDir, className + ".java");
                try (FileReader reader = new FileReader(sourceFile);) {
                    char[] buffer = new char[(int) sourceFile.length()];
                    reader.read(buffer);
                    String source = String.valueOf(buffer);
                    int start = source.indexOf("package");
                    start = source.indexOf("/*", start);
                    int end = source.indexOf("* For a list of all");
                    System.out.println(source.substring(start, end - 3));
                    boolean skip = false;
                    String platform = SWT.getPlatform();
                    if (source.contains("PocketPC")) {
                        platform = "PocketPC";
                        skip = true;
                    } else if (source.contains("OpenGL")) {
                        platform = "OpenGL";
                        skip = true;
                    } else if (source.contains("JavaXPCOM")) {
                        platform = "JavaXPCOM";
                        skip = true;
                    } else {
                        String[] platforms = { "win32", "gtk" };
                        for (int p = 0; p < platforms.length; p++) {
                            if (!platforms[p].equals(platform) && source.contains("." + platforms[p])) {
                                platform = platforms[p];
                                skip = true;
                                break;
                            }
                        }
                    }
                    if (skip) {
                        System.out.println("...skipping " + platform + " example...");
                        continue;
                    }
                } catch (Exception e) {
                }
            }
            Method method = null;
            String[] param = SnippetsConfig.getSnippetArguments(i);
            try {
                method = clazz.getMethod("main", param.getClass());
            } catch (NoSuchMethodException e) {
                System.out.println("   Did not find main(String [])");
            }
            if (method != null) {
                try {
                    method.invoke(clazz, new Object[] { param });
                } catch (IllegalAccessException e) {
                    System.out.println("   Failed to launch (illegal access)");
                } catch (IllegalArgumentException e) {
                    System.out.println("   Failed to launch (illegal argument to main)");
                } catch (InvocationTargetException e) {
                    System.out.println("   Exception in Snippet: " + e.getTargetException());
                }
            }
        }
    }
}