1
22
23 package com.liferay.portal.kernel.util;
24
25 import java.io.BufferedReader;
26 import java.io.File;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.Reader;
30 import java.io.StreamTokenizer;
31
32 import java.util.HashSet;
33 import java.util.Set;
34
35
41 public class ClassUtil {
42
43 public static Set<String> getClasses(File file) throws IOException {
44 String fileName = file.getName();
45
46 if (fileName.endsWith(".java")) {
47 fileName = fileName.substring(0, fileName.length() - 5);
48 }
49
50 return getClasses(new FileReader(file), fileName);
51 }
52
53 public static Set<String> getClasses(Reader reader, String className)
54 throws IOException {
55
56 Set<String> classes = new HashSet<String>();
57
58 StreamTokenizer st = new StreamTokenizer(new BufferedReader(reader));
59
60 st.resetSyntax();
61 st.slashSlashComments(true);
62 st.slashStarComments(true);
63 st.wordChars('a', 'z');
64 st.wordChars('A', 'Z');
65 st.wordChars('.', '.');
66 st.wordChars('0', '9');
67 st.wordChars('_', '_');
68 st.lowerCaseMode(false);
69 st.eolIsSignificant(false);
70 st.quoteChar('"');
71 st.quoteChar('\'');
72 st.parseNumbers();
73
74 while (st.nextToken() != StreamTokenizer.TT_EOF) {
75 if (st.ttype == StreamTokenizer.TT_WORD) {
76 if (st.sval.equals("class") || st.sval.equals("interface")) {
77 break;
78 }
79 }
80 }
81
82 while (st.nextToken() != StreamTokenizer.TT_EOF) {
83 if (st.ttype == StreamTokenizer.TT_WORD) {
84 if (st.sval.indexOf('.') >= 0) {
85 classes.add(st.sval.substring(0, st.sval.indexOf('.')));
86 }
87 else {
88 classes.add(st.sval);
89 }
90 }
91 else if (st.ttype != StreamTokenizer.TT_NUMBER &&
92 st.ttype != StreamTokenizer.TT_EOL) {
93
94 if (Character.isUpperCase((char)st.ttype)) {
95 classes.add(String.valueOf((char)st.ttype));
96 }
97 }
98 }
99
100 classes.remove(className);
101
102 return classes;
103 }
104
105 public static boolean isSubclass(Class<?> a, Class<?> b) {
106 if (a == b) {
107 return true;
108 }
109
110 if (a == null || b == null) {
111 return false;
112 }
113
114 for (Class<?> x = a; x != null; x = x.getSuperclass()) {
115 if (x == b) {
116 return true;
117 }
118
119 if (b.isInterface()) {
120 Class<?>[] interfaces = x.getInterfaces();
121
122 for (int i = 0; i < interfaces.length; i++) {
123 if (isSubclass(interfaces[i], b)) {
124 return true;
125 }
126 }
127 }
128 }
129
130 return false;
131 }
132
133 public static boolean isSubclass(Class<?> a, String s) {
134 if (a == null || s == null) {
135 return false;
136 }
137
138 if (a.getName().equals(s)) {
139 return true;
140 }
141
142 for (Class<?> x = a; x != null; x = x.getSuperclass()) {
143 if (x.getName().equals(s)) {
144 return true;
145 }
146
147 Class<?>[] interfaces = x.getInterfaces();
148
149 for (int i = 0; i < interfaces.length; i++) {
150 if (isSubclass(interfaces[i], s)) {
151 return true;
152 }
153 }
154 }
155
156 return false;
157 }
158
159 }