How to run a class from Jar which is not the Main-Class in its Manifest file

后端 未结 7 2235
情深已故
情深已故 2020-11-28 01:39

I have a JAR with 4 classes, each one has Main method. I want to be able to run each one of those as per the need. I am trying to run it from command-line on Linux box.

7条回答
  •  再見小時候
    2020-11-28 02:18

    Apart from calling java -jar myjar.jar com.mycompany.Myclass, you can also make the main class in your Manifest a Dispatcher class.

    Example:

    public class Dispatcher{
    
        private static final Map> ENTRY_POINTS =
            new HashMap>();
        static{
            ENTRY_POINTS.put("foo", Foo.class);
            ENTRY_POINTS.put("bar", Bar.class);
            ENTRY_POINTS.put("baz", Baz.class);
        }
    
        public static void main(final String[] args) throws Exception{
    
            if(args.length < 1){
                // throw exception, not enough args
            }
            final Class entryPoint = ENTRY_POINTS.get(args[0]);
            if(entryPoint==null){
                // throw exception, entry point doesn't exist
            }
            final String[] argsCopy =
                args.length > 1
                    ? Arrays.copyOfRange(args, 1, args.length)
                    : new String[0];
            entryPoint.getMethod("main", String[].class).invoke(null,
                (Object) argsCopy);
    
        }
    }
    

提交回复
热议问题