33
import java.lang.StringBuilder;
35
public class AccessModifiers {
36
public int errorCount;
37
protected String protectedField;
39
private String privateField;
41
public static void main(String[] args) throws Exception {
42
new AccessModifiers().run();
45
private void run() throws Exception {
46
List<String> pubMembers = new ArrayList<String>();
47
pubMembers.add("public int errorCount");
48
pubMembers.add("public AccessModifiers");
49
pubMembers.add("public static void main");
51
List<String> proMembers = new ArrayList<String>();
52
proMembers.add("protected java.lang.String protectedField");
53
proMembers.add("protected java.lang.String runJavap");
55
List<String> pkgMembers = new ArrayList<String>();
56
pkgMembers.add("java.lang.String packageField");
57
pkgMembers.add("boolean verify");
58
pkgMembers.add("void error");
60
List<String> priMembers = new ArrayList<String>();
61
priMembers.add("private java.lang.String privateField");
62
priMembers.add("private void run() throws java.lang.Exception");
63
priMembers.add("private void test");
65
List<String> expectedList = new ArrayList<String>();
67
expectedList.addAll(pubMembers);
68
test("-public", expectedList);
70
expectedList.addAll(proMembers);
71
test("-protected", expectedList);
73
expectedList.addAll(pkgMembers);
74
test("-package", expectedList);
76
expectedList.addAll(priMembers);
77
test("-private", expectedList);
80
throw new Exception(errorCount + " errors received");
83
private void test(String option, List<String> expectedStrs) throws Exception {
84
String output = runJavap(0, option);
85
if (verify(output, expectedStrs))
86
System.out.println(option + " test passed");
89
protected String runJavap(int expect, String... options) {
91
List<String> optlist = new ArrayList<String>();
92
optlist.addAll(Arrays.asList(options));
93
optlist.add("AccessModifiers");
94
String[] newoptions = optlist.toArray(new String[optlist.size()]);
95
StringWriter sw = new StringWriter();
96
PrintWriter pw = new PrintWriter(sw);
97
System.out.printf("\nRun javap " + optlist + "\n\n");
98
int rc = com.sun.tools.javap.Main.run(newoptions, pw);
100
System.out.println(sw);
102
throw new Error("Expect to return " + expect + ", but return " + rc);
103
return sw.toString();
106
boolean verify(String output, List<String> expects) {
108
for (String expect: expects) {
109
if (!output.contains(expect)) {
110
error(expect + " not found");
117
void error(String msg) {
118
System.err.println(msg);