How to call main() method of a class using reflection in java

前端 未结 2 480
你的背包
你的背包 2021-01-03 02:30

When calling the main method of a Java class from another main method using reflection,

Class thisClass = loader.loadClass(packClassName);
Method thisMethod          


        
相关标签:
2条回答
  • 2021-01-03 02:45

    For your stated requirements (dynamically invoke the main method of a random class, with reflection you have alot of unnecessary code.

    • You do not need to invoke a constructor for the class
    • You do not need to introspect the classes fields
    • Since you are invoking a static method, you do not even need a real object to invoke the method on

    You can adapt the following code to meet your needs:

    try {
        final Class<?> clazz = Class.forName("blue.RandomClass");
        final Method method = clazz.getMethod("main", String[].class);
    
        final Object[] args = new Object[1];
        args[0] = new String[] { "1", "2"};
        method.invoke(null, args);
    } catch (final Exception e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-01-03 02:48

    Perceptions answer looks correct; if you need load from a Jar not in the class path you can use a URL class loader

         try {
            URL[] urls;
            URLClassLoader urlLoader;
    
            urls = ...;
    
            urlLoader = new URLClassLoader(urls);
    
            @SuppressWarnings("rawtypes")
            Class runClass = urlLoader.loadClass(classToRun);
    
            Object[] arguments = new Object[]{args};
            Method mainMethod = runClass.getMethod("main", String[].class);
            mainMethod.invoke(null, arguments);
          } catch (Exception e) {
            e.printStackTrace();
          }
    
    0 讨论(0)
提交回复
热议问题