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

前端 未结 2 488
你的背包
你的背包 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: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();
          }
    

提交回复
热议问题