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:com.aliyun.odps.mapred.cli.Cli.java

public static void main(String[] args) {
    SessionState ss = SessionState.get();
    OptionParser parser = new OptionParser(ss);
    try {/* ww w .j  a v  a  2  s  .com*/
        parser.parse(args);
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    } catch (ClassNotFoundException e) {
        System.err.println("Class not found:" + e.getMessage());
        System.exit(-1);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        parser.usage();
        System.exit(-1);
    } catch (OdpsException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    try {
        Method main = parser.getMainClass().getMethod("main", String[].class);
        main.invoke(null, (Object) parser.getArguments());
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t != null && t instanceof OdpsException) {
            OdpsException ex = (OdpsException) t;
            System.err.println(ex.getErrorCode() + ":" + ex.getMessage());
            System.exit(-1);
        } else {
            throw new RuntimeException("Unknown error", e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

static public void main(String args[]) throws Exception {
    URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"), new URL("http://www.java2s.edu/~xyx/test/") };
    URLClassLoader x = new URLClassLoader(myurl);
    Class c = x.loadClass("TestURL");

    Class getArg1[] = { (new String[1]).getClass() };
    Method m = c.getMethod("main", getArg1);
    String[] my1 = { "arg1 passed", "arg2 passed" };
    Object myarg1[] = { my1 };/*from  w  ww  . j  a v  a 2 s  . c  om*/
    m.invoke(null, myarg1);

    Object ob = c.newInstance();
    Class arg2[] = {};
    Method m2 = c.getMethod("tt", arg2);
    m2.invoke(ob, null);

    Class arg3[] = { (new String()).getClass(), int.class };
    Method m3 = c.getMethod("tt", arg3);
    Object myarg2[] = { "Arg1", new Integer(100) };
    m3.invoke(ob, myarg2);
}

From source file:ClassLoaderDemo0.java

public static void main(String[] argv) {
    System.out.println("ClassLoaderDemo starting");
    ClassLoaderDemo0 loader = new ClassLoaderDemo0();
    Class c = null;/*from   w  w w . j  a  va2 s . co  m*/
    Object demo;
    try {
        /* Load the "Demo" class from memory */

        System.out.println("About to load class  Demo");
        c = loader.loadClass("Demo", true);
        System.out.println("About to instantiate class Demo");
        demo = c.newInstance();
        System.out.println("Got Demo class loaded: " + demo);

        /* Now try to call a method */

        Method mi = c.getMethod("test", null);
        mi.invoke(demo, null);

    } catch (InvocationTargetException e) {
        // The invoked method threw an exception. We get it
        // wrapped up inside another exception, hence the
        // extra call here:
        e.getTargetException().printStackTrace();
        System.out.println("Could not run test method");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Could not run test method");
    }
}

From source file:org.jasig.portlet.data.Importer.java

public static void main(String[] args) throws Exception {
    String dir = args[0];/*  w  ww.  j  a v  a2 s. co m*/
    String importExportContext = args[1];
    String sessionFactoryBeanName = args[2];
    String modelClassName = args[3];
    String serviceBeanName = args[4];
    String serviceBeanMethodName = args[5];

    ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext);
    SessionFactory sessionFactory = context.getBean(sessionFactoryBeanName, SessionFactory.class);
    Class<?> modelClass = Class.forName(modelClassName);
    Object service = context.getBean(serviceBeanName);

    JAXBContext jc = JAXBContext.newInstance(modelClass);

    File folder = new File(dir);
    File[] files = folder.listFiles(new ImportFileFilter());

    for (File f : files) {
        StreamSource xml = new StreamSource(f.getAbsoluteFile());
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        JAXBElement je1 = unmarshaller.unmarshal(xml, modelClass);
        Object object = je1.getValue();
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();

        Method method = service.getClass().getMethod(serviceBeanMethodName, modelClass);
        method.invoke(service, object);
        transaction.commit();
    }
}

From source file:org.jasig.portlet.data.Exporter.java

public static void main(String[] args) throws Exception {
    String dir = args[0];//from  w  ww. j  av a2s .  c o  m
    String importExportContext = args[1];
    String sessionFactoryBeanName = args[2];
    String modelClassName = args[3];
    String serviceBeanName = args[4];
    String serviceBeanMethodName = args[5];

    ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext);
    SessionFactory sessionFactory = context.getBean(sessionFactoryBeanName, SessionFactory.class);
    Class<?> modelClass = Class.forName(modelClassName);

    Object service = context.getBean(serviceBeanName);
    Session session = sessionFactory.getCurrentSession();
    Transaction transaction = session.beginTransaction();

    JAXBContext jc = JAXBContext.newInstance(modelClass);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Method method = service.getClass().getMethod(serviceBeanMethodName);
    List<?> objects = (List<?>) method.invoke(service, null);

    for (Object o : objects) {
        session.lock(o, LockMode.NONE);
        JAXBElement je2 = new JAXBElement(new QName(modelClass.getSimpleName().toLowerCase()), modelClass, o);
        String output = dir + File.separator + UUID.randomUUID().toString() + ".xml";
        try {
            marshaller.marshal(je2, new FileOutputStream(output));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    transaction.commit();
}

From source file:CompileString.java

public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String program = "class Test{" + "   public static void main (String [] args){"
            + "      System.out.println (\"Hello, World\");" + "      System.out.println (args.length);"
            + "   }" + "}";

    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = getJavaSourceFromString(program);

    compiler.getTask(null, null, null, null, null, fileObjects).call();

    Class<?> clazz = Class.forName("Test");
    Method m = clazz.getMethod("main", new Class[] { String[].class });
    Object[] _args = new Object[] { new String[0] };
    m.invoke(null, _args);
}

From source file:org.jetbrains.webdemo.executors.JavaExecutor.java

public static void main(String[] args) {
    PrintStream defaultOutputStream = System.out;
    try {/*from   ww w .j a v  a 2 s.  c  om*/
        System.setOut(new PrintStream(standardOutputStream));
        System.setErr(new PrintStream(errorOutputStream));

        RunOutput outputObj = new RunOutput();
        String className;
        if (args.length > 0) {
            className = args[0];
            try {
                Method mainMethod = Class.forName(className).getMethod("main", String[].class);
                mainMethod.invoke(null, (Object) Arrays.copyOfRange(args, 1, args.length));
            } catch (InvocationTargetException e) {
                outputObj.exception = e.getCause();
            } catch (NoSuchMethodException e) {
                System.err.println("No main method found in project.");
            } catch (ClassNotFoundException e) {
                System.err.println("No main method found in project.");
            }
        } else {
            System.err.println("No main method found in project.");
        }

        System.out.flush();
        System.err.flush();
        System.setOut(defaultOutputStream);
        outputObj.text = outputStream.toString().replaceAll("</errStream><errStream>", "")
                .replaceAll("</outStream><outStream>", "");
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Throwable.class, new ThrowableSerializer());
        objectMapper.registerModule(module);
        System.out.print(objectMapper.writeValueAsString(outputObj));
    } catch (Throwable e) {
        System.setOut(defaultOutputStream);
        System.out.println("{\"text\":\"<errStream>" + e.getClass().getName() + ": " + e.getMessage());
        System.out.print("</errStream>\"}");
    }

}

From source file:TasteOfThingsV1.java

 public static void main(String args[]) throws Exception {
   prepareData();//from w w w .ja  va2 s  .  c o m

   HashBag myBag = new HashBag(testMap.values());

   System.err.println("How many Boxes? " + myBag.getCount("Boxes"));
   myBag.add("Boxes", 5);
   System.err.println("How many Boxes now? " + myBag.getCount("Boxes"));

   Method method =
     testBean.getClass().getDeclaredMethod("getTestMap", new Class[0]);
   HashMap reflectionMap =
     (HashMap)method.invoke(testBean, new Object[0]);
   System.err.println("The value of the 'squ' key using reflection: " +
     reflectionMap.get("squ"));

   String squ = BeanUtils.getMappedProperty(testBean, "testMap", "squ");
   squ = StringUtils.capitalize(squ);

   PropertyUtils.setMappedProperty(testBean, "testMap", "squ", squ);

   System.err.println("The value of the 'squ' key is: " +
     BeanUtils.getMappedProperty(testBean, "testMap", "squ"));

   String box = (String)testMap.get("box");
   String caps =
     Character.toTitleCase(box.charAt(0)) +
     box.substring(1, box.length());
   System.err.println("Capitalizing boxes by Java: " + caps);
}

From source file:it.doqui.index.ecmengine.test.AllTests.java

public static void main(String[] args) {
    Log logger = LogFactory.getLog(ECMENGINE_TEST_LOG_CATEGORY);
    logger.debug("[AllTests::main] BEGIN");
    String runner;/*from  w  w  w . j a  va 2 s  .c o  m*/
    int i;
    String arguments[];
    Class cls;

    runner = null;
    for (i = 0; (i < args.length) && (null == runner); i++) {
        if (args[i].equalsIgnoreCase("-text"))
            runner = "junit.textui.TestRunner";
        else if (args[i].equalsIgnoreCase("-awt"))
            runner = "junit.awtui.TestRunner";
        else if (args[i].equalsIgnoreCase("-swing"))
            runner = "junit.swingui.TestRunner";
    }
    if (null != runner) {
        // remove it from the arguments
        arguments = new String[args.length - 1];
        System.arraycopy(args, 0, arguments, 0, i - 1);
        System.arraycopy(args, i, arguments, i - 1, args.length - i);
        args = arguments;
    } else
        runner = "junit.swingui.TestRunner";

    // append the test class
    arguments = new String[args.length + 1];
    System.arraycopy(args, 0, arguments, 0, args.length);
    arguments[args.length] = "it.doqui.index.ecmengine.test.AllTests";

    // invoke main() of the test runner
    try {
        cls = Class.forName(runner);
        java.lang.reflect.Method method = cls.getDeclaredMethod("main", new Class[] { String[].class });
        method.invoke(null, new Object[] { arguments });
    } catch (Throwable t) {
        logger.debug("[AllTests::main] Problem in test execution : " + t);
    } finally {
        logger.debug("[AllTests::main] BEGIN");

    }
}

From source file:Main.java

public static void main(String... args) {
    try {//from w  ww  . j a va2 s.c  om
        Class<?> c = Class.forName(args[0]);
        Class[] argTypes = new Class[] { String[].class };
        Method main = c.getDeclaredMethod("main", argTypes);
        String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
        System.out.format("invoking %s.main()%n", c.getName());
        main.invoke(null, (Object) mainArgs);

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchMethodException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (InvocationTargetException x) {
        x.printStackTrace();
    }
}