提交 | 用户 | 时间
|
149dd0
|
1 |
package com.iailab.netsdk.common; |
H |
2 |
|
|
3 |
import java.lang.reflect.Method; |
|
4 |
import java.util.NoSuchElementException; |
|
5 |
import java.util.Scanner; |
|
6 |
import java.util.Vector; |
|
7 |
|
|
8 |
public class CaseMenu { |
|
9 |
|
|
10 |
public static class Item { |
|
11 |
private Object object; |
|
12 |
private String itemName; |
|
13 |
private String methodName; |
|
14 |
|
|
15 |
public Item(Object object, String itemName, String methodName) { |
|
16 |
super(); |
|
17 |
this.object = object; |
|
18 |
this.itemName = itemName; |
|
19 |
this.methodName = methodName; |
|
20 |
} |
|
21 |
|
|
22 |
public Object getObject() { |
|
23 |
return object; |
|
24 |
} |
|
25 |
|
|
26 |
public String getItemName() { |
|
27 |
return itemName; |
|
28 |
} |
|
29 |
|
|
30 |
public String getMethodName() { |
|
31 |
return methodName; |
|
32 |
} |
|
33 |
} |
|
34 |
|
|
35 |
private Vector<Item> items; |
|
36 |
|
|
37 |
public CaseMenu() { |
|
38 |
super(); |
|
39 |
items = new Vector<Item>(); |
|
40 |
} |
|
41 |
|
|
42 |
public void addItem(Item item) { |
|
43 |
items.add(item); |
|
44 |
} |
|
45 |
|
|
46 |
private void showItem() { |
|
47 |
final String format = "%2d\t%-20s\n"; |
|
48 |
int index = 0; |
|
49 |
System.out.printf(format, index++, "exit App"); |
|
50 |
for (Item item : items) { |
|
51 |
System.out.printf(format, index++, item.getItemName()); |
|
52 |
} |
|
53 |
System.out.println("Please input a item index to invoke the method:"); |
|
54 |
} |
|
55 |
|
|
56 |
public void run() { |
|
57 |
Scanner scanner = new Scanner(System.in); |
|
58 |
while(true) { |
|
59 |
showItem(); |
|
60 |
try { |
|
61 |
int input = Integer.parseInt(scanner.nextLine()); |
|
62 |
|
|
63 |
if (input <= 0 ) { |
|
64 |
System.err.println("input <= 0 || scanner.nextLine() == null"); |
|
65 |
// scanner.close(); |
|
66 |
// System.exit(0); |
|
67 |
break; |
|
68 |
} |
|
69 |
|
|
70 |
if (input < 0 || input > items.size()) { |
|
71 |
System.err.println("Input Error Item Index."); |
|
72 |
continue; |
|
73 |
} |
|
74 |
|
|
75 |
Item item = items.get(input - 1); |
|
76 |
Class<?> itemClass = item.getObject().getClass(); |
|
77 |
Method method = itemClass.getMethod(item.getMethodName()); |
|
78 |
method.invoke(item.getObject()); |
|
79 |
} catch (NoSuchElementException e) { |
|
80 |
// scanner.close(); |
|
81 |
// System.exit(0); |
|
82 |
break; |
|
83 |
} catch (NumberFormatException e) { |
|
84 |
System.err.println("Input Error NumberFormat."); |
|
85 |
continue; |
|
86 |
} catch (Exception e) { |
|
87 |
e.printStackTrace(); |
|
88 |
} |
|
89 |
} |
|
90 |
|
|
91 |
scanner.close(); |
|
92 |
} |
|
93 |
} |