/Users/lyon/j4p/src/javassist/CtNewClass.java
|
1 /*
2 * Javassist, a Java-bytecode translator toolkit.
3 * Copyright (C) 1999-2003 Shigeru Chiba. All Rights Reserved.
4 *
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. Alternatively, the contents of this file may be used under
8 * the terms of the GNU Lesser General Public License Version 2.1 or later.
9 *
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
14 */
15
16 package javassist;
17
18 import java.io.DataOutputStream;
19 import java.io.IOException;
20
21 import javassist.bytecode.ClassFile;
22
23 class CtNewClass extends CtClassType {
24 /* true if the class is an interface.
25 */
26 protected boolean hasConstructor;
27
28 CtNewClass(String name, ClassPool cp,
29 boolean isInterface, CtClass superclass) {
30 super(name, cp);
31 wasChanged = true;
32 eraseCache();
33 String superName;
34 if (superclass == null)
35 superName = null;
36 else
37 superName = superclass.getName();
38
39 classfile = new ClassFile(isInterface, name, superName);
40
41 setModifiers(Modifier.setPublic(getModifiers()));
42 hasConstructor = isInterface;
43 }
44
45 public void addConstructor(CtConstructor c)
46 throws CannotCompileException {
47 hasConstructor = true;
48 super.addConstructor(c);
49 }
50
51 void toBytecode(DataOutputStream out)
52 throws CannotCompileException, IOException {
53 if (!hasConstructor)
54 try {
55 inheritAllConstructors();
56 } catch (NotFoundException e) {
57 throw new CannotCompileException(e);
58 }
59
60 super.toBytecode(out);
61 }
62
63 /**
64 * Adds constructors inhrited from the super class.
65 *
66 * <p>After this method is called, the class inherits all the
67 * constructors from the super class. The added constructor
68 * calls the super's constructor with the same signature.
69 */
70 public void inheritAllConstructors()
71 throws CannotCompileException, NotFoundException {
72 CtClass superclazz;
73 CtConstructor[] cs;
74
75 superclazz = getSuperclass();
76 cs = superclazz.getDeclaredConstructors();
77
78 int n = 0;
79 for (int i = 0; i < cs.length; ++i) {
80 CtConstructor c = cs[i];
81 if (Modifier.isPublic(c.getModifiers())) {
82 CtConstructor cons
83 = CtNewConstructor.make(c.getParameterTypes(),
84 c.getExceptionTypes(), this);
85 addConstructor(cons);
86 ++n;
87 }
88 }
89
90 if (n < 1)
91 throw new CannotCompileException(
92 "no public constructor in " + superclazz.getName());
93
94 }
95 }
96