1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package examples;
20
21 import java.lang.reflect.Method;
22 import java.security.CodeSource;
23 import java.util.Enumeration;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.jar.JarEntry;
27 import java.util.jar.JarFile;
28
29 public class Main {
30
31
32
33
34
35
36
37
38
39
40
41
42 public static void main(String[] args) throws Exception {
43 if (args.length==0) {
44 System.out.println("Usage: java -jar examples.jar <exampleClass> <exampleClass parameters>");
45 }
46 CodeSource codeSource = Main.class.getProtectionDomain().getCodeSource();
47 Map<String, String> map = new HashMap<String, String>();
48 if ( codeSource != null) {
49 final String sourceFile = codeSource.getLocation().getFile();
50 if (sourceFile.endsWith(".jar")) {
51 if (args.length==0) {
52 System.out.println("\nClasses found in the jar:");
53 }
54 JarFile jf = new JarFile(sourceFile);
55 Enumeration<JarEntry> e = jf.entries();
56 while (e.hasMoreElements()) {
57 JarEntry je = e.nextElement();
58 String name = je.getName();
59 if (!name.endsWith(".class")
60 || name.contains("$")
61 || name.equals("examples/nntp/NNTPUtils.class")
62 || name.equals("examples/util/IOUtil.class")
63 || name.equals("examples/Main.class")) {
64 continue;
65 }
66 name = name.replace(".class", "");
67 int lastSep = name.lastIndexOf('/');
68 String alias = name.substring(lastSep+1);
69 if (args.length==0) {
70 System.out.printf("%-25s %s%n",alias,name);
71 }
72 map.put(alias, name);
73 }
74 jf.close();
75 }
76 }
77
78 if (args.length==0) {
79 return;
80 }
81
82 String shortName = args[0];
83 String fullName = map.get(shortName);
84 if (fullName == null) {
85 fullName = shortName;
86 }
87 fullName = fullName.replace('/', '.');
88 Class<?> clazz = Class.forName(fullName);
89 Method m = clazz.getDeclaredMethod("main", new Class[]{args.getClass()});
90 String[] args2 = new String[args.length-1];
91 System.arraycopy(args, 1, args2, 0, args2.length);
92 m.invoke(null, (Object)args2);
93 }
94 }