5 import java.util.zip.*;
6 import java.util.jar.*;
8 import java.lang.reflect.*;
10 import org.eclipse.jdt.core.compiler.IProblem;
11 import org.eclipse.jdt.internal.compiler.ClassFile;
12 import org.eclipse.jdt.internal.compiler.CompilationResult;
13 //import org.eclipse.jdt.internal.compiler.Compiler;
14 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
15 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
16 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
17 import org.eclipse.jdt.internal.compiler.IProblemFactory;
18 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
19 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
20 import org.eclipse.jdt.internal.compiler.env.*;
21 import org.eclipse.jdt.internal.compiler.impl.*;
22 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
24 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
26 public class Compiler {
27 // Static Entry Point /////////////////////////////////////////////////////
29 public static void main(String[] args) throws IOException {
30 boolean verbose = false, veryverbose = false;
31 List srcdir = new ArrayList();
32 String source = null, target = null, blddir = null, mainclass = null;
33 boolean buildjar = false;
35 if (args.length == 0) args = new String[] { "--help" };
36 for (int i=0; i < args.length; i++) {
37 if (args[i].charAt(0) == '-') {
38 if (args[i].length() == 1) {
39 System.out.println("Illegal switch: -"); return; }
40 switch (args[i].charAt(1)) {
42 if (args[i].equals("--help")) printHelp();
43 else System.out.println("Unknown switch: -");
46 if (i == args.length - 1) {
47 System.out.println("Missing parameter: "+args[i]); return; }
48 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
52 if (i == args.length - 1) {
53 System.out.println("Missing parameter: "+args[i]); return; }
54 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
59 if (i == args.length - 1) {
60 System.out.println("Missing parameter: "+args[i]); return; }
61 mainclass = args[++i];
64 if (i == args.length - 1) {
65 System.out.println("Missing parameter: "+args[i]); return; }
69 if (i == args.length - 1) {
70 System.out.println("Missing parameter: "+args[i]); return; }
83 } else srcdir.add(args[i]);
86 Compiler c = new Compiler();
88 if (buildjar) c.setBuildJar(blddir);
89 else c.setBuildDir(blddir);
91 if (source != null) c.setSource(source);
92 if (target != null) c.setTarget(target);
93 if (mainclass != null) c.setMainClass(mainclass);
95 String[] s = new String[srcdir.size()];
99 c.setVerbose(verbose);
100 c.setVeryVerbose(veryverbose);
103 private static void printHelp() {
104 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
105 System.out.println("Options:");
106 System.out.println(" -d <directory> Directory to put generated class files in");
107 System.out.println(" -j <jarfile> Jar file to put generated class files in");
108 System.out.println(" -m <class> Main-Class for jar file.");
109 System.out.println(" -s <release> Compile with specified source compatibility.");
110 System.out.println(" -t <release> Compile with specified class file compatibility.");
111 System.out.println(" -v Verbose output.");
112 System.out.println(" -V Very Verbose output.");
113 System.out.println(" -h or --help Print this message.");
114 System.out.println("");
118 // Compiler Interface /////////////////////////////////////////////////////
120 private ClassLoader loader = ClassLoader.getSystemClassLoader();
121 private Map loaded = new HashMap();
122 private PrintWriter out = new PrintWriter(System.out);
123 private Preprocessor preprocessor;
125 private Source[] sources;
127 private File builddir = null;
128 private boolean buildzip = false;
129 private ZipOutputStream jarfile = null;
130 private String mainclass = null;
132 private String[] sourcedirs = new String[0];
134 private PrintWriter warn;
135 private boolean hasErrors;
136 private boolean verbose = false;
137 private boolean veryverbose = false;
140 List defs = Collections.EMPTY_LIST;
142 String define = System.getProperty("org.ibex.tool.preprocessor.define");
143 if (define != null) {
144 defs = new ArrayList();
145 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
146 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
149 preprocessor = new Preprocessor(null, null, defs);
152 public void setMainClass(String mainclass) { this.mainclass = mainclass; }
153 public void setBuildJar(String dir) throws IOException {
154 builddir = new File(dir == null ? "." : dir);
157 public void setBuildDir(String dir) throws IOException {
158 builddir = new File(dir == null ? "." : dir);
161 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
163 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
164 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
166 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
167 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
169 public void setVerbose(boolean v) { verbose = v; }
170 public void setVeryVerbose(boolean v) { veryverbose = v; }
172 public void compile() throws IOException {
173 List s = new ArrayList();
176 Manifest m = new Manifest();
177 m.getMainAttributes().putValue("Manifest-Version", "1.0");
178 if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
179 jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
181 for (int i=0; i < sourcedirs.length; i++) {
182 File src = new File(sourcedirs[i]);
184 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
187 filterSources(s, src, new char[0][], sourcedirs[i]);
190 if (veryverbose) System.out.println("working with "+s.size() +" sources");
191 sources = new Source[s.size()]; s.toArray(sources);
192 ICompilationUnit[] units = new ICompilationUnit[s.size()];
193 int u = 0; for (int i=0; i < sources.length; i++)
194 if (sources[i].compiled == null) units[u++] = sources[i].unit;
195 if (u != units.length) {
196 ICompilationUnit[] newu = new ICompilationUnit[u];
197 System.arraycopy(units, 0, newu, 0, u);
203 StringWriter sw = new StringWriter();
204 StringBuffer w = sw.getBuffer();
205 warn = new PrintWriter(sw);
207 org.eclipse.jdt.internal.compiler.Compiler jdt =
208 new org.eclipse.jdt.internal.compiler.Compiler(
209 env, policy, settings, results, problems);
212 if (!hasErrors) { out.write(w.toString()); out.flush(); }
215 if (jarfile != null) jarfile.close();
216 } catch (Exception e) {
219 if (verbose) System.out.print(clearing + " \r");
222 private final FilenameFilter filterSrcs = new FilenameFilter() {
223 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
225 private final FileFilter filterDirs = new FileFilter() {
226 public boolean accept(File path) { return path.isDirectory(); }
228 private byte[] bytes(File bfile) {
229 byte[] bytes = new byte[2 * 1024];
232 InputStream bin = new FileInputStream(bfile);
233 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
235 if (pos == bytes.length) {
236 byte[] newbytes= new byte[pos * 2];
237 System.arraycopy(bytes, 0, newbytes, 0, pos);
242 } catch (IOException e) {
243 System.out.println("Error reading class file"); // FIXME
244 e.printStackTrace(); return null;
247 if (pos != bytes.length) {
248 byte[] newbytes= new byte[pos * 2];
249 System.arraycopy(bytes, 0, newbytes, 0, pos);
255 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
256 List bclasses = new ArrayList();
257 File bdir = new File(builddir, str(pack, File.separatorChar));
259 // add the java files in this directory
260 File[] ja = dir.listFiles(filterSrcs);
261 for (int i=0; i < ja.length; i++) {
262 char[] n = name(classname(ja[i].getName()));
263 Source src = new Source(ja[i], n, pack, srcdir);
265 // skip the file if the build version is newer than the source
266 String bclass = new String(n);
267 File bfile = new File(bdir, bclass + ".class");
268 if (bfile.lastModified() > ja[i].lastModified()) {
269 src.compiled = bytes(bfile);
270 bclasses.add(bclass);
276 // process the inner classes of any binary files
277 for (int i=0; i < bclasses.size(); i++) {
278 final String bc = (String)bclasses.get(i);
279 final FilenameFilter f = new FilenameFilter() {
280 public boolean accept(File dir, String name) {
281 return name.length() > bc.length() && name.startsWith(bc) &&
282 name.charAt(bc.length()) == '$' && name.endsWith(".class");
285 File[] bfile = bdir.listFiles(f);
286 for (int j=0; j < bfile.length; j++) {
287 Source src = new Source(bfile[j],
288 name(classname(bfile[j].getName())), pack, srcdir);
289 src.compiled = bytes(bfile[j]);
294 // add the subdirectories as packages
295 File[] d = dir.listFiles(filterDirs);
296 for (int i=0; i < d.length; i++) {
297 char[][] newpack = new char[pack.length + 1][];
298 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
299 newpack[pack.length] = d[i].getName().toCharArray();
300 filterSources(s, d[i], newpack, srcdir);
305 /** Represents a file to be compiled. */
308 char[] n; char[][] p;
310 char[] processed = null;
311 byte[] compiled = null;
312 ClassFileReader reader = null;
314 final ICompilationUnit unit = new ICompilationUnit() {
315 public char[] getMainTypeName() { return n; }
316 public char[][] getPackageName() { return p; }
317 public char[] getFileName() { return fileName; }
318 public char[] getContents() {
319 if (processed != null) return processed;
322 Reader r = new InputStreamReader(new BufferedInputStream(
323 new FileInputStream(orig)));
324 StringWriter w = new StringWriter();
327 synchronized (preprocessor) {
328 preprocessor.setReader(r);
329 preprocessor.setWriter(w);
330 err = preprocessor.process();
333 if (err.size() > 0) {
334 for (int i=0; i < err.size(); i++) {
335 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
336 out.print(getFileName());
338 out.print(warn.getLine());
340 out.print(warn instanceof Preprocessor.Error ?
341 " error: " : " warning: ");
342 out.println(warn.getMessage());
347 processed = w.toString().toCharArray();
348 } catch (IOException e) {
349 System.out.println("IOException: "+e); // FIXME
357 private Source(File o, char[] n, char[][] p, String srcdir) {
358 orig = o; this.n = n; this.p = p;
359 String file = srcdir;
360 file += File.separatorChar + str(p, File.separatorChar);
361 file += File.separatorChar + new String(n) + ".java";
362 fileName = file.toCharArray();
366 // ClassLoader Wrappers ///////////////////////////////////////////////////
368 final static class LoadedNestedType implements IBinaryNestedType {
370 LoadedNestedType(Class c) { this.c = c; }
371 public char[] getName() { return name(c); }
372 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
373 public int getModifiers() { return c.getModifiers(); }
376 final static class LoadedField implements IBinaryField {
380 LoadedField(Field f) {
382 int m = f.getModifiers();
384 c = Constant.NotAConstant;
385 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
387 Class type = f.getType();
388 if (type == Boolean.TYPE) {
389 c = new BooleanConstant(f.getBoolean(null));
390 } else if (type == Byte.TYPE) {
391 c = new ByteConstant(f.getByte(null));
392 } else if (type == Character.TYPE) {
393 c = new CharConstant(f.getChar(null));
394 } else if (type == Double.TYPE) {
395 c = new DoubleConstant(f.getDouble(null));
396 } else if (type == Float.TYPE) {
397 c = new FloatConstant(f.getFloat(null));
398 } else if (type == Integer.TYPE) {
399 c = new IntConstant(f.getInt(null));
400 } else if (type == Long.TYPE) {
401 c = new LongConstant(f.getLong(null));
402 } else if (type == Short.TYPE) {
403 c = new ShortConstant(f.getShort(null));
404 } else if (type == String.class) {
405 c = new StringConstant((String)f.get(null));
407 } catch (IllegalAccessException e) {}
410 public Constant getConstant() { return c; }
411 public char[] getTypeName() { return typeName(f.getType()); }
412 public char[] getName() { return f.getName().toCharArray(); }
413 public int getModifiers() { return f.getModifiers(); }
416 final static class LoadedConstructor implements IBinaryMethod {
417 private Constructor c;
421 LoadedConstructor(Constructor c) {
424 Class[] exs = c.getExceptionTypes();
425 ex = new char[exs.length][];
426 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
428 desc = descriptor(c.getParameterTypes(), null);
430 public int getModifiers() { return c.getModifiers(); }
431 public char[] getSelector() { return c.getName().toCharArray(); }
432 public boolean isConstructor() { return true; }
433 public boolean isClinit() { return false; }
434 public char[][] getArgumentNames() { return null; }
435 public char[][] getExceptionTypeNames() { return ex; }
436 public char[] getMethodDescriptor() { return desc; }
439 final static class LoadedMethod implements IBinaryMethod {
444 LoadedMethod(Method m) {
447 Class[] exs = m.getExceptionTypes();
448 ex = new char[exs.length][];
449 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
451 desc = descriptor(m.getParameterTypes(), m.getReturnType());
453 public int getModifiers() { return m.getModifiers(); }
454 public char[] getSelector() { return m.getName().toCharArray(); }
455 public boolean isConstructor() { return false; }
456 public boolean isClinit() { return false; }
457 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
458 public char[][] getExceptionTypeNames() { return ex; }
459 public char[] getMethodDescriptor() { return desc; }
462 final static class LoadedClass implements IBinaryType {
464 private IBinaryField[] f;
465 private char[][] inf;
466 private IBinaryNestedType[] nested;
467 private IBinaryMethod[] meth = null;
469 LoadedClass(Class c) {
472 Field[] fields = c.getDeclaredFields();
473 List flist = new ArrayList(fields.length);
474 for (int i=0; i < fields.length; i++)
475 if (!Modifier.isPrivate(fields[i].getModifiers()))
476 flist.add(new LoadedField(fields[i]));
477 f = new IBinaryField[flist.size()];
480 Class[] interfaces = c.getInterfaces();
481 inf = new char[interfaces.length][];
482 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
484 Class[] classes = c.getClasses();
485 nested = new IBinaryNestedType[classes.length];
486 for (int i=0; i < nested.length; i++)
487 nested[i] = new LoadedNestedType(classes[i]);
489 Constructor[] constructors = c.getDeclaredConstructors();
490 Method[] methods = c.getDeclaredMethods();
491 if (methods.length + constructors.length > 0) {
492 List m = new ArrayList(methods.length + constructors.length);
493 for (int j=0; j < methods.length; j++)
494 if (!Modifier.isPrivate(methods[j].getModifiers()))
495 m.add(new LoadedMethod(methods[j]));
496 for (int j=0; j < constructors.length; j++)
497 if (!Modifier.isPrivate(constructors[j].getModifiers()))
498 m.add(new LoadedConstructor(constructors[j]));
499 meth = new IBinaryMethod[m.size()]; m.toArray(meth);
503 public char[] getName() { return name(c); }
504 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
505 public char[] getSuperclassName() { return name(c.getSuperclass()); }
506 public IBinaryField[] getFields() { return f; }
507 public char[][] getInterfaceNames() { return inf; }
508 public IBinaryNestedType[] getMemberTypes() { return nested; }
509 public IBinaryMethod[] getMethods() { return meth; }
510 public int getModifiers() { return c.getModifiers(); }
512 public boolean isBinaryType() { return true; }
513 public boolean isClass() { return true; }
514 public boolean isInterface() { return c.isInterface(); }
515 public boolean isAnonymous() { return false; }
516 public boolean isLocal() { return false; } // FIXME
517 public boolean isMember() { return false; } // FIXME
518 public char[] sourceFileName() { return null; }
519 public char[] getFileName() { return null; }
521 public boolean equals(Object o) {
522 return o == this || super.equals(o) ||
523 (o != null && o instanceof LoadedClass &&
524 c.equals(((LoadedClass)o).c));
529 // Compiler Parameters ////////////////////////////////////////////////////
531 /** Used by compiler to resolve classes. */
532 final INameEnvironment env = new INameEnvironment() {
533 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
534 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
535 if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
538 Class c = Class.forName(str(p, '.') + '.' + new String(n));
539 if (veryverbose) System.out.println(" found in classloader: "+ c);
540 IBinaryType b = (IBinaryType)loaded.get(c);
541 if (b == null) loaded.put(c, b = new LoadedClass(c));
542 return new NameEnvironmentAnswer(b);
543 } catch (ClassNotFoundException e) {}
545 // cut out searches for java.* packages in sources list
546 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
547 if (veryverbose) System.out.println(" not found, unknown java.*");
552 for (int i=0; i < sources.length; i++) {
553 Source s = sources[i];
554 if (eq(n, s.n) && eq(p, s.p)) {
555 if (s.reader != null) {
556 if (veryverbose) System.out.println(" found reader");
557 return new NameEnvironmentAnswer(s.reader);
559 if (s.compiled != null) {
560 if (veryverbose) System.out.println(" found compiled, new reader");
561 s.reader = new ClassFileReader(s.compiled,
562 s.orig.getName().toCharArray(), true);
563 return new NameEnvironmentAnswer(s.reader);
565 if (veryverbose) System.out.println(" found unit");
566 return new NameEnvironmentAnswer(sources[i].unit);
569 } catch (ClassFormatException e) {
570 System.out.println("Unexpected ClassFormatException"); // FIXME
571 e.printStackTrace(); return null;
573 if (veryverbose) System.out.println(" not found");
576 public boolean isPackage(char[][] parent, char[] name) {
577 if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
578 String parentName = str(parent, '/');
579 for (int i=0; i < sources.length; i++) {
580 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
581 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
584 loader.getResource(parentName + ".class") == null &&
585 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
587 public void cleanup() {}
590 /** Used by compiler to decide what do with problems.. */
591 private final IErrorHandlingPolicy policy =
592 DefaultErrorHandlingPolicies.proceedWithAllProblems();
594 /** Used by compiler for general options. */
595 private final Map settings = new HashMap();
597 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
598 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
599 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
600 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
603 /** Used by compiler for processing compiled classes and their errors. */
604 private final ICompilerRequestor results = new ICompilerRequestor() {
605 public void acceptResult(CompilationResult result) {
606 if (veryverbose) System.out.println("got result: "+result);
607 if (result.hasProblems()) {
609 IProblem[] p = result.getProblems();
611 for (int i=0; i < p.length; i++) {
612 if (p[i].isError()) { o = out; err = true; }
615 o.print(p[i].getOriginatingFileName());
617 o.print(p[i].getSourceLineNumber());
619 o.print(p[i].isError() ? " error: " : " warning: ");
620 o.println(p[i].getMessage());
623 if (err) { hasErrors = true; return; }
626 ClassFile[] c = result.getClassFiles();
627 for (int i=0; i < c.length; i++) {
629 char[][] name = c[i].getCompoundName();
634 while (pct.length() < 2) pct = " " + pct;
635 pct = "(" + pct + "%) ";
637 String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
638 if (clearing.length() < printme.length()) clearing = "";
639 else clearing = clearing.substring(printme.length());
640 System.out.print(printme + clearing + "\r");
641 for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
645 jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
646 jarfile.write(c[i].getBytes());
647 } catch (java.util.zip.ZipException ze) {
648 // HACK: horrendous hack
649 if (ze.getMessage().indexOf("duplicate entry") != -1) {
650 //System.out.println("compiler emitted class twice: " + new String(name(name)));
656 // build package path to new class file
657 File path = new File(builddir, str(pack(name), '/'));
658 if (!path.exists()) path.mkdirs();
659 // write new class file
660 path = new File(path, new String(name(name)) + ".class");
661 OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
662 o.write(c[i].getBytes());
665 } catch (IOException e) {
666 System.out.println("IOException writing class"); // FIXME
674 String clearing = "";
676 /** Problem creater for compiler. */
677 private final IProblemFactory problems = new DefaultProblemFactory();
680 // Helper Functiosn ///////////////////////////////////////////////////////
682 /** Convert source file path into class name block.
683 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
684 private char[][] classname(String name) {
685 String delim = name.indexOf('/') == -1 ? "." : "/";
687 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
688 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
689 if (name.startsWith(delim)) name = name.substring(1);
691 StringTokenizer st = new StringTokenizer(name, delim);
692 char[][] n = new char[st.countTokens()][];
693 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
697 /** Convert class name into a String. */
698 private static String str(char[][] name, char delim) {
699 StringBuffer b = new StringBuffer();
700 for (int i=0; name != null && i < name.length; i++) {
701 if (name[i] == null || name[i].length == 0) continue;
702 if (i > 0) b.append(delim);
708 /** Returns the package component of a class name.
709 * Effectively returns char[length - 1][]. */
710 private static char[][] pack(char[][] c) {
711 char[][] p = new char[c.length - 1][];
712 for (int i=0; i < p.length; i++) p[i] = c[i];
716 /** Returns the direct-name component of a class name.
717 * eg. String from java.lang.String */
718 private static char[] name(char[][] c) { return c[c.length - 1]; }
720 /** Returns true of contents of both char arrays are equal. */
721 private static boolean eq(char[][] c1, char[][] c2) {
722 if (c1 == null || c2 == null) return c1 == c2;
723 if (c1.length != c2.length) return false;
724 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
728 /** Returns true of contents of both char arrays are equal. */
729 private static boolean eq(char[] c1, char[] c2) {
730 if (c1 == null || c2 == null) return c1 == c2;
731 if (c1.length != c2.length) return false;
732 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
736 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
737 private static char[] name(Class c) {
738 return c == null ? null : c.getName().replace('.', '/').toCharArray();
741 /** Returns the type name of a class as per VM Spec 4.3.2. */
742 private static char[] typeName(Class p) {
743 StringBuffer sb = new StringBuffer();
745 return sb.toString().toCharArray();
748 /** Returns the type name of a class as per VM Spec 4.3.2.
749 * eg. int -> I, String -> Ljava/lang/String; */
750 private static void typeName(Class p, StringBuffer sb) {
751 String name = p.getName();
752 switch (name.charAt(0)) {
753 case 'B': case 'C': case 'D': case 'F': case 'I':
754 case 'J': case 'S': case 'Z': case 'V': case '[':
755 sb.append(name(p)); break;
757 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
758 if (name.equals("byte")) { sb.append('B'); break; }
759 case 'c': if (name.equals("char")) { sb.append('C'); break; }
760 case 'd': if (name.equals("double")) { sb.append('D'); break; }
761 case 'f': if (name.equals("float")) { sb.append('F'); break; }
762 case 'i': if (name.equals("int")) { sb.append('I'); break; }
763 case 'l': if (name.equals("long")) { sb.append('J'); break; }
764 case 's': if (name.equals("short")) { sb.append('S'); break; }
765 case 'v': if (name.equals("void")) { sb.append('V'); break; }
767 sb.append('L'); sb.append(name(p)); sb.append(';');
771 /** Returns the descriptor of a method per VM Spec 4.3.3.
772 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
773 private static char[] descriptor(Class[] p, Class r) {
774 StringBuffer sb = new StringBuffer();
776 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
778 if (r != null) typeName(r, sb);
779 return sb.toString().toCharArray();