KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javassist > CtClass


1 /*
2  * Javassist, a Java-bytecode translator toolkit.
3  * Copyright (C) 1999-2005 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 javassist.bytecode.ClassFile;
19 import javassist.bytecode.Descriptor;
20 import javassist.bytecode.Opcode;
21 import javassist.expr.ExprEditor;
22
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.DataOutputStream JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.Collection JavaDoc;
32
33 // Subclasses of CtClass: CtClassType, CtPrimitiveType, and CtArray
34

35 /**
36  * An instance of <code>CtClass</code> represents a class.
37  * It is obtained from <code>ClassPool</code>.
38  *
39  * @see ClassPool#get(String)
40  */

41 public abstract class CtClass {
42     protected String JavaDoc qualifiedName;
43
44     /**
45      * The version number of this release.
46      */

47     public static final String JavaDoc version = "3.0";
48
49     /**
50      * Prints the version number and the copyright notice.
51      *
52      * <p>The following command invokes this method:
53      *
54      * <ul><pre>java -jar javassist.jar</pre></ul>
55      */

56     public static void main(String JavaDoc[] args) {
57         System.out.println("Javassist version " + CtClass.version);
58         System.out.println("Copyright (C) 1999-2005 Shigeru Chiba."
59                            + " All Rights Reserved.");
60     }
61
62     static final String JavaDoc javaLangObject = "java.lang.Object";
63
64     /**
65      * The <code>CtClass</code> object representing
66      * the <code>boolean</code> type.
67      */

68     public static CtClass booleanType;
69
70     /**
71      * The <code>CtClass</code> object representing
72      * the <code>char</code> type.
73      */

74     public static CtClass charType;
75
76     /**
77      * The <code>CtClass</code> object representing
78      * the <code>byte</code> type.
79      */

80     public static CtClass byteType;
81
82     /**
83      * The <code>CtClass</code> object representing
84      * the <code>short</code> type.
85      */

86     public static CtClass shortType;
87
88     /**
89      * The <code>CtClass</code> object representing
90      * the <code>int</code> type.
91      */

92     public static CtClass intType;
93
94     /**
95      * The <code>CtClass</code> object representing
96      * the <code>long</code> type.
97      */

98     public static CtClass longType;
99
100     /**
101      * The <code>CtClass</code> object representing
102      * the <code>float</code> type.
103      */

104     public static CtClass floatType;
105
106     /**
107      * The <code>CtClass</code> object representing
108      * the <code>double</code> type.
109      */

110     public static CtClass doubleType;
111
112     /**
113      * The <code>CtClass</code> object representing
114      * the <code>void</code> type.
115      */

116     public static CtClass voidType;
117
118     static CtClass[] primitiveTypes;
119
120     static {
121         primitiveTypes = new CtClass[9];
122
123         booleanType =
124             new CtPrimitiveType("boolean", 'Z', "java.lang.Boolean",
125                                 "booleanValue", "()Z", Opcode.IRETURN,
126                                 Opcode.T_BOOLEAN, 1);
127         primitiveTypes[0] = booleanType;
128
129         charType = new CtPrimitiveType("char", 'C', "java.lang.Character",
130                                        "charValue", "()C", Opcode.IRETURN,
131                                        Opcode.T_CHAR, 1);
132         primitiveTypes[1] = charType;
133
134         byteType = new CtPrimitiveType("byte", 'B', "java.lang.Byte",
135                                        "byteValue", "()B", Opcode.IRETURN,
136                                        Opcode.T_BYTE, 1);
137         primitiveTypes[2] = byteType;
138
139         shortType = new CtPrimitiveType("short", 'S', "java.lang.Short",
140                                         "shortValue", "()S", Opcode.IRETURN,
141                                         Opcode.T_SHORT, 1);
142         primitiveTypes[3] = shortType;
143
144         intType = new CtPrimitiveType("int", 'I', "java.lang.Integer",
145                                       "intValue", "()I", Opcode.IRETURN,
146                                       Opcode.T_INT, 1);
147         primitiveTypes[4] = intType;
148
149         longType = new CtPrimitiveType("long", 'J', "java.lang.Long",
150                                        "longValue", "()J", Opcode.LRETURN,
151                                        Opcode.T_LONG, 2);
152         primitiveTypes[5] = longType;
153
154         floatType = new CtPrimitiveType("float", 'F', "java.lang.Float",
155                                         "floatValue", "()F", Opcode.FRETURN,
156                                         Opcode.T_FLOAT, 1);
157         primitiveTypes[6] = floatType;
158
159         doubleType = new CtPrimitiveType("double", 'D', "java.lang.Double",
160                                          "doubleValue", "()D", Opcode.DRETURN,
161                                          Opcode.T_DOUBLE, 2);
162         primitiveTypes[7] = doubleType;
163
164         voidType = new CtPrimitiveType("void", 'V', "java.lang.Void",
165                                        null, null, Opcode.RETURN, 0, 0);
166         primitiveTypes[8] = voidType;
167     }
168
169     protected CtClass(String JavaDoc name) {
170         qualifiedName = name;
171     }
172
173     /**
174      * Converts the object to a string.
175      */

176     public String JavaDoc toString() {
177         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(getClass().getName());
178         buf.append("@");
179         buf.append(Integer.toHexString(hashCode()));
180         buf.append("[");
181         extendToString(buf);
182         buf.append("]");
183         return buf.toString();
184     }
185
186     /**
187      * Implemented in subclasses to add to the {@link #toString()} result.
188      * Subclasses should put a space before each token added to the buffer.
189      */

190     protected void extendToString(StringBuffer JavaDoc buffer) {
191         buffer.append(getName());
192     }
193
194     /**
195      * Returns a <code>ClassPool</code> for this class.
196      */

197     public ClassPool getClassPool() { return null; }
198
199     /**
200      * Returns a class file for this class.
201      *
202      * <p>This method is not available if <code>isFrozen()</code>
203      * is true.
204      */

205     public ClassFile getClassFile() {
206         checkModify();
207         return getClassFile2();
208     }
209
210     /**
211      * Undocumented method. Do not use; internal-use only.
212      */

213     public ClassFile getClassFile2() { return null; }
214
215     /**
216      * Undocumented method. Do not use; internal-use only.
217      */

218     public javassist.compiler.AccessorMaker getAccessorMaker() {
219         return null;
220     }
221
222     /**
223      * Returns the uniform resource locator (URL) of the class file.
224      */

225     public URL JavaDoc getURL() throws NotFoundException {
226         throw new NotFoundException(getName());
227     }
228
229     /**
230      * Returns true if the definition of the class has been modified.
231      */

232     public boolean isModified() { return false; }
233
234     /**
235      * Returns true if the class has been loaded or written out
236      * and thus it cannot be modified any more.
237      *
238      * @see #defrost()
239      */

240     public boolean isFrozen() { return true; }
241
242     void freeze() {}
243
244     void checkModify() throws RuntimeException JavaDoc {
245         if (isFrozen())
246             throw new RuntimeException JavaDoc(getName() + " class is frozen");
247
248         // isModified() must return true after this method is invoked.
249
}
250
251     /**
252      * Defrosts the class so that the class can be modified again.
253      *
254      * <p>To avoid changes that will be never reflected,
255      * the class is frozen to be unmodifiable if it is loaded or
256      * written out. This method should be called only in a case
257      * that the class will be reloaded or written out later again.
258      *
259      * <p>If <code>defrost()</code> will be called later, pruning
260      * must be disallowed in advance.
261      *
262      * @see #isFrozen()
263      * @see #stopPruning(boolean)
264      */

265     public void defrost() {
266         throw new RuntimeException JavaDoc("cannot defrost " + getName());
267     }
268
269     /**
270      * Disallows (or allows) pruning the data structure on memory
271      * when this <code>CtClass</code> object is converted into a class file.
272      * Pruning saves memory space since a <code>ClassPool</code> holds
273      * all instances of <code>CtClass</code>
274      * all the time of program execution.
275      * However, pruning discards the data representing part of the
276      * class definition, such as method bodies.
277      * Therefore, once it is pruned, <code>toBytecode()</code>,
278      * <code>writeFile()</code>, or <code>toClass()</code> cannot
279      * be called again.
280      *
281      * <p>Initially, pruning is allowed.
282      *
283      * @param stop disallow pruning if true. Otherwise, allow.
284      * @see #detach()
285      * @see #toBytecode()
286      * @see #toClass()
287      * @see #writeFile()
288      */

289     public void stopPruning(boolean stop) {}
290
291     /* Called by get() in ClassPool.
292      * CtClassType overrides this method.
293      */

294     void incGetCounter() {}
295
296     /**
297      * Returns <code>true</code> if this object represents a primitive
298      * Java type: boolean, byte, char, short, int, long, float, double,
299      * or void.
300      */

301     public boolean isPrimitive() { return false; }
302
303     /**
304      * Returns <code>true</code> if this object represents an array type.
305      */

306     public boolean isArray() {
307         return false;
308     }
309
310     /**
311      * If this object represents an array, this method returns the component
312      * type of the array. Otherwise, it returns <code>null</code>.
313      */

314     public CtClass getComponentType() throws NotFoundException {
315         return null;
316     }
317
318     /**
319      * Returns <code>true</code> if this class extends or implements
320      * <code>clazz</code>. It also returns <code>true</code> if
321      * this class is the same as <code>clazz</code>.
322      */

323     public boolean subtypeOf(CtClass clazz) throws NotFoundException {
324         return this == clazz || getName().equals(clazz.getName());
325     }
326
327     /**
328      * Obtains the fully-qualified name of the class.
329      */

330     public String JavaDoc getName() { return qualifiedName; }
331
332     /**
333      * Obtains the not-qualified class name.
334      */

335     public final String JavaDoc getSimpleName() {
336         String JavaDoc qname = qualifiedName;
337         int index = qname.lastIndexOf('.');
338         if (index < 0)
339             return qname;
340         else
341             return qname.substring(index + 1);
342     }
343
344     /**
345      * Obtains the package name. It may be <code>null</code>.
346      */

347     public final String JavaDoc getPackageName() {
348         String JavaDoc qname = qualifiedName;
349         int index = qname.lastIndexOf('.');
350         if (index < 0)
351             return null;
352         else
353             return qname.substring(0, index);
354     }
355
356     /**
357      * Sets the class name
358      *
359      * @param name fully-qualified name
360      */

361     public void setName(String JavaDoc name) {
362         checkModify();
363         if (name != null)
364             qualifiedName = name;
365     }
366
367     /**
368      * Substitutes <code>newName</code> for all occurrences of a class
369      * name <code>oldName</code> in the class file.
370      *
371      * @param oldName replaced class name
372      * @param newName substituted class name
373      */

374     public void replaceClassName(String JavaDoc oldName, String JavaDoc newName) {
375         checkModify();
376     }
377
378     /**
379      * Changes class names appearing in the class file according to the
380      * given <code>map</code>.
381      *
382      * <p>All the class names appearing in the class file are tested
383      * with <code>map</code> to determine whether each class name is
384      * replaced or not. Thus this method can be used for collecting
385      * all the class names in the class file. To do that, first define
386      * a subclass of <code>ClassMap</code> so that <code>get()</code>
387      * records all the given parameters. Then, make an instance of
388      * that subclass as an empty hash-table. Finally, pass that instance
389      * to this method. After this method finishes, that instance would
390      * contain all the class names appearing in the class file.
391      *
392      * @param map the hashtable associating replaced class names
393      * with substituted names.
394      */

395     public void replaceClassName(ClassMap map) {
396         checkModify();
397     }
398
399     /**
400      * Returns a collection of the names of all the classes
401      * referenced in this class.
402      * That collection includes the name of this class.
403      *
404      * <p>This method may return <code>null</code>.
405      */

406     public Collection JavaDoc getRefClasses() {
407         ClassFile cf = getClassFile2();
408         if (cf != null) {
409             ClassMap cm = new ClassMap() {
410                 public void put(String JavaDoc oldname, String JavaDoc newname) {
411                     put0(oldname, newname);
412                 }
413
414                 public Object JavaDoc get(Object JavaDoc jvmClassName) {
415                     String JavaDoc n = toJavaName((String JavaDoc)jvmClassName);
416                     put0(n, n);
417                     return null;
418                 }
419
420                 public void fix(String JavaDoc name) {}
421             };
422             cf.renameClass(cm);
423             return cm.values();
424         }
425         else
426             return null;
427     }
428
429     /**
430      * Determines whether this object represents a class or an interface.
431      * It returns <code>true</code> if this object represents an interface.
432      */

433     public boolean isInterface() {
434         return false;
435     }
436
437     /**
438      * Returns the modifiers for this class, encoded in an integer.
439      * For decoding, use <code>javassist.Modifier</code>.
440      *
441      * @see Modifier
442      */

443     public int getModifiers() {
444         return 0;
445     }
446
447     /**
448      * Sets the modifiers.
449      *
450      * @param mod modifiers encoded by
451      * <code>javassist.Modifier</code>
452      * @see Modifier
453      */

454     public void setModifiers(int mod) {
455         checkModify();
456     }
457
458     /**
459      * Determines whether the class directly or indirectly extends
460      * the given class. If this class extends a class A and
461      * the class A extends a class B, then subclassof(B) returns true.
462      *
463      * <p>This method returns true if the given class is identical to
464      * the class represented by this object.
465      */

466     public boolean subclassOf(CtClass superclass) {
467         return false;
468     }
469
470     /**
471      * Obtains the class object representing the superclass of the
472      * class.
473      * It returns null if this object represents the
474      * <code>java.lang.Object</code> class and thus it does not have
475      * the super class.
476      *
477      * <p>If this object represents an interface, this method
478      * always returns the <code>java.lang.Object</code> class.
479      * To obtain the super interfaces
480      * extended by that interface, call <code>getInterfaces()</code>.
481      */

482     public CtClass getSuperclass() throws NotFoundException {
483         return null;
484     }
485
486     /**
487      * Changes a super class unless this object represents an interface.
488      * The new super class must be compatible with the old one.
489      *
490      * <p>If this object represents an interface, this method is equivalent
491      * to <code>addInterface()</code>; it appends <code>clazz</code> to
492      * the list of the super interfaces extended by that interface.
493      * Note that an interface can extend multiple super interfaces.
494      */

495     public void setSuperclass(CtClass clazz) throws CannotCompileException {
496         checkModify();
497     }
498
499     /**
500      * Obtains the class objects representing the interfaces implemented
501      * by the class or, if this object represents an interface, the interfaces
502      * extended by that interface.
503      */

504     public CtClass[] getInterfaces() throws NotFoundException {
505         return new CtClass[0];
506     }
507
508     /**
509      * Sets implemented interfaces. If this object represents an interface,
510      * this method sets the interfaces extended by that interface.
511      *
512      * @param list a list of the <code>CtClass</code> objects
513      * representing interfaces, or
514      * <code>null</code> if the class implements
515      * no interfaces.
516      */

517     public void setInterfaces(CtClass[] list) {
518         checkModify();
519     }
520
521     /**
522      * Adds an interface.
523      *
524      * @param anInterface the added interface.
525      */

526     public void addInterface(CtClass anInterface) {
527         checkModify();
528     }
529
530     /**
531      * If this class is a member class or interface of another class,
532      * then the class enclosing this class is returned.
533      *
534      * @return null if this class is a top-level class or an anonymous class.
535      */

536     public CtClass getDeclaringClass() throws NotFoundException {
537         return null;
538     }
539
540     /**
541      * Returns the immediately enclosing class of this class.
542      * This method works only with JDK 1.5 or later.
543      *
544      * @return null if this class is a top-level class.
545      */

546     public CtClass getEnclosingClass() throws NotFoundException {
547         return null;
548     }
549
550     /**
551      * Makes a new nested class. Making a nested class modifies the
552      * data in this <code>CtClass</code>.
553      *
554      * <p>The current implementation only supports a static nested class.
555      * <code>isStatic</code> must be true.
556      *
557      * @param name the simple name of the nested class.
558      * @param isStatic true if the nested class is static.
559      */

560     public CtClass makeNestedClass(String JavaDoc name, boolean isStatic) {
561         throw new RuntimeException JavaDoc(getName() + " is not a class");
562     }
563
564     /**
565      * Returns an array containing <code>CtField</code> objects
566      * representing all the public fields of the class.
567      * That array includes public fields inherited from the
568      * superclasses.
569      */

570     public CtField[] getFields() { return new CtField[0]; }
571
572     /**
573      * Returns the field with the specified name. The returned field
574      * may be a private field declared in a super class or interface.
575      */

576     public CtField getField(String JavaDoc name) throws NotFoundException {
577         throw new NotFoundException(name);
578     }
579
580     /**
581      * @return null if the specified field is not found.
582      */

583     CtField getField2(String JavaDoc name) { return null; }
584
585     /**
586      * Gets all the fields declared in the class. The inherited fields
587      * are not included.
588      *
589      * <p>Note: the result does not include inherited fields.
590      */

591     public CtField[] getDeclaredFields() { return new CtField[0]; }
592
593     /**
594      * Retrieves the field with the specified name among the fields
595      * declared in the class.
596      *
597      * <p>Note: this method does not search the superclasses.
598      */

599     public CtField getDeclaredField(String JavaDoc name) throws NotFoundException {
600         throw new NotFoundException(name);
601     }
602
603     /**
604      * Gets all the constructors and methods declared in the class.
605      */

606     public CtBehavior[] getDeclaredBehaviors() {
607         return new CtBehavior[0];
608     }
609
610     /**
611      * Returns an array containing <code>CtConstructor</code> objects
612      * representing all the public constructors of the class.
613      */

614     public CtConstructor[] getConstructors() {
615         return new CtConstructor[0];
616     }
617
618     /**
619      * Returns the constructor with the given signature,
620      * which is represented by a character string
621      * called method descriptor.
622      * For details of the method descriptor, see the JVM specification
623      * or <code>javassist.bytecode.Descriptor</code>.
624      *
625      * @param desc method descriptor
626      * @see javassist.bytecode.Descriptor
627      */

628     public CtConstructor getConstructor(String JavaDoc desc)
629         throws NotFoundException
630     {
631         throw new NotFoundException("no such a constructor");
632     }
633
634     /**
635      * Gets all the constructors declared in the class.
636      *
637      * @see javassist.CtConstructor
638      */

639     public CtConstructor[] getDeclaredConstructors() {
640         return new CtConstructor[0];
641     }
642
643     /**
644      * Returns a constructor receiving the specified parameters.
645      *
646      * @param params parameter types.
647      */

648     public CtConstructor getDeclaredConstructor(CtClass[] params)
649         throws NotFoundException
650     {
651         String JavaDoc desc = Descriptor.ofConstructor(params);
652         return getConstructor(desc);
653     }
654
655     /**
656      * Gets the class initializer (static constructor)
657      * declared in the class.
658      * This method returns <code>null</code> if
659      * no class initializer is not declared.
660      *
661      * @see #makeClassInitializer()
662      * @see javassist.CtConstructor
663      */

664     public CtConstructor getClassInitializer() {
665         return null;
666     }
667
668     /**
669      * Returns an array containing <code>CtMethod</code> objects
670      * representing all the public methods of the class.
671      * That array includes public methods inherited from the
672      * superclasses.
673      */

674     public CtMethod[] getMethods() {
675         return new CtMethod[0];
676     }
677
678     /**
679      * Returns the method with the given name and signature.
680      * The returned method may be declared in a super class.
681      * The method signature is represented by a character string
682      * called method descriptor,
683      * which is defined in the JVM specification.
684      *
685      * @param name method name
686      * @param desc method descriptor
687      * @see javassist.bytecode.Descriptor
688      */

689     public CtMethod getMethod(String JavaDoc name, String JavaDoc desc)
690         throws NotFoundException
691     {
692         throw new NotFoundException(name);
693     }
694
695     /**
696      * Gets all methods declared in the class. The inherited methods
697      * are not included.
698      *
699      * @see javassist.CtMethod
700      */

701     public CtMethod[] getDeclaredMethods() {
702         return new CtMethod[0];
703     }
704
705     /**
706      * Retrieves the method with the specified name and parameter types
707      * among the methods declared in the class.
708      *
709      * <p>Note: this method does not search the superclasses.
710      *
711      * @param name method name
712      * @param params parameter types
713      * @see javassist.CtMethod
714      */

715     public CtMethod getDeclaredMethod(String JavaDoc name, CtClass[] params)
716         throws NotFoundException
717     {
718         throw new NotFoundException(name);
719     }
720
721     /**
722      * Retrieves the method with the specified name among the methods
723      * declared in the class. If there are multiple methods with
724      * the specified name, then this method returns one of them.
725      *
726      * <p>Note: this method does not search the superclasses.
727      *
728      * @see javassist.CtMethod
729      */

730     public CtMethod getDeclaredMethod(String JavaDoc name) throws NotFoundException {
731         throw new NotFoundException(name);
732     }
733
734     /**
735      * Makes an empty class initializer (static constructor).
736      * If the class already includes a class initializer,
737      * this method returns it.
738      *
739      * @see #getClassInitializer()
740      */

741     public CtConstructor makeClassInitializer()
742         throws CannotCompileException
743     {
744         throw new CannotCompileException("not a class");
745     }
746
747     /**
748      * Adds a constructor. To add a class initializer (static constructor),
749      * call <code>makeClassInitializer()</code>.
750      *
751      * @see #makeClassInitializer()
752      */

753     public void addConstructor(CtConstructor c)
754         throws CannotCompileException
755     {
756         checkModify();
757     }
758
759     /**
760      * Removes a constructor declared in this class.
761      *
762      * @param c removed constructor.
763      * @throws NotFoundException if the constructor is not found.
764      */

765     public void removeConstructor(CtConstructor c) throws NotFoundException {
766         checkModify();
767     }
768
769     /**
770      * Adds a method.
771      */

772     public void addMethod(CtMethod m) throws CannotCompileException {
773         checkModify();
774     }
775
776     /**
777      * Removes a method declared in this class.
778      *
779      * @param m removed method.
780      * @throws NotFoundException if the method is not found.
781      */

782     public void removeMethod(CtMethod m) throws NotFoundException {
783         checkModify();
784      }
785
786     /**
787      * Adds a field.
788      *
789      * <p>The <code>CtField</code> belonging to another
790      * <code>CtClass</code> cannot be directly added to this class.
791      * Only a field created for this class can be added.
792      *
793      * @see javassist.CtField#CtField(CtField,CtClass)
794      */

795     public void addField(CtField f) throws CannotCompileException {
796         addField(f, (CtField.Initializer)null);
797     }
798
799     /**
800      * Adds a field with an initial value.
801      *
802      * <p>The <code>CtField</code> belonging to another
803      * <code>CtClass</code> cannot be directly added to this class.
804      * Only a field created for this class can be added.
805      *
806      * <p>The initial value is given as an expression written in Java.
807      * Any regular Java expression can be used for specifying the initial
808      * value. The followings are examples.
809      *
810      * <ul><pre>
811      * cc.addField(f, "0") // the initial value is 0.
812      * cc.addField(f, "i + 1") // i + 1.
813      * cc.addField(f, "new Point()"); // a Point object.
814      * </pre></ul>
815      *
816      * <p>Here, the type of variable <code>cc</code> is <code>CtClass</code>.
817      * The type of <code>f</code> is <code>CtField</code>.
818      *
819      * @param init an expression for the initial value.
820      *
821      * @see javassist.CtField.Initializer#byExpr(String)
822      * @see javassist.CtField#CtField(CtField,CtClass)
823      */

824     public void addField(CtField f, String JavaDoc init)
825         throws CannotCompileException
826     {
827         checkModify();
828     }
829
830     /**
831      * Adds a field with an initial value.
832      *
833      * <p>The <code>CtField</code> belonging to another
834      * <code>CtClass</code> cannot be directly added to this class.
835      * Only a field created for this class can be added.
836      *
837      * <p>For example,
838      *
839      * <ul><pre>
840      * CtClass cc = ...;
841      * addField(new CtField(CtClass.intType, "i", cc),
842      * CtField.Initializer.constant(1));
843      * </pre></ul>
844      *
845      * <p>This code adds an <code>int</code> field named "i". The
846      * initial value of this field is 1.
847      *
848      * @param init specifies the initial value of the field.
849      *
850      * @see javassist.CtField#CtField(CtField,CtClass)
851      */

852     public void addField(CtField f, CtField.Initializer init)
853         throws CannotCompileException
854     {
855         checkModify();
856     }
857
858     /**
859      * Removes a field declared in this class.
860      *
861      * @param f removed field.
862      * @throws NotFoundException if the field is not found.
863      */

864     public void removeField(CtField f) throws NotFoundException {
865         checkModify();
866     }
867
868     /**
869      * Obtains an attribute with the given name.
870      * If that attribute is not found in the class file, this
871      * method returns null.
872      *
873      * <p>This is a convenient method mainly for obtaining
874      * a user-defined attribute. For dealing with attributes, see the
875      * <code>javassist.bytecode</code> package. For example, the following
876      * expression returns all the attributes of a class file.
877      *
878      * <ul><pre>
879      * getClassFile().getAttributes()
880      * </pre></ul>
881      *
882      * @param name attribute name
883      * @see javassist.bytecode.AttributeInfo
884      */

885     public byte[] getAttribute(String JavaDoc name) {
886         return null;
887     }
888
889     /**
890      * Adds a named attribute.
891      * An arbitrary data (smaller than 64Kb) can be saved in the class
892      * file. Some attribute name are reserved by the JVM.
893      * The attributes with the non-reserved names are ignored when a
894      * class file is loaded into the JVM.
895      * If there is already an attribute with
896      * the same name, this method substitutes the new one for it.
897      *
898      * <p>This is a convenient method mainly for adding
899      * a user-defined attribute. For dealing with attributes, see the
900      * <code>javassist.bytecode</code> package. For example, the following
901      * expression adds an attribute of a class file.
902      *
903      * <ul><pre>
904      * getClassFile().addAttribute(info)
905      * </pre></ul>
906      *
907      * @param name attribute name
908      * @param data attribute value
909      * @see javassist.bytecode.AttributeInfo
910      */

911     public void setAttribute(String JavaDoc name, byte[] data) {
912         checkModify();
913     }
914
915     /**
916      * Applies the given converter to all methods and constructors
917      * declared in the class. This method calls <code>instrument()</code>
918      * on every <code>CtMethod</code> and <code>CtConstructor</code> object
919      * in the class.
920      *
921      * @param converter specifies how to modify.
922      */

923     public void instrument(CodeConverter converter)
924         throws CannotCompileException
925     {
926         checkModify();
927     }
928
929     /**
930      * Modifies the bodies of all methods and constructors
931      * declared in the class. This method calls <code>instrument()</code>
932      * on every <code>CtMethod</code> and <code>CtConstructor</code> object
933      * in the class.
934      *
935      * @param editor specifies how to modify.
936      */

937     public void instrument(ExprEditor editor)
938         throws CannotCompileException
939     {
940         checkModify();
941     }
942
943     /**
944      * Converts this class to a <code>java.lang.Class</code> object.
945      * Once this method is called, further modifications are not
946      * allowed any more.
947      * To load the class, this method uses the context class loader
948      * of the current thread. If the program is running on some application
949      * server, the context class loader might be inappropriate to load the
950      * class.
951      *
952      * <p>This method is provided for convenience. If you need more
953      * complex functionality, you should write your own class loader.
954      *
955      * <p>Note: this method calls <code>toClass()</code>
956      * in <code>ClassPool</code>.
957      *
958      * @see #toClass(java.lang.ClassLoader)
959      * @see ClassPool#toClass(CtClass)
960      */

961     public Class JavaDoc toClass() throws CannotCompileException {
962         return getClassPool().toClass(this);
963     }
964
965     /**
966      * Converts this class to a <code>java.lang.Class</code> object.
967      * Once this method is called, further modifications are not allowed
968      * any more.
969      *
970      * <p>The class file represented by this <code>CtClass</code> is
971      * loaded by the given class loader to construct a
972      * <code>java.lang.Class</code> object. Since a private method
973      * on the class loader is invoked through the reflection API,
974      * the caller must have permissions to do that.
975      *
976      * <p>This method is provided for convenience. If you need more
977      * complex functionality, you should write your own class loader.
978      *
979      * <p>Note: this method calls <code>toClass()</code>
980      * in <code>ClassPool</code>.
981      *
982      * @param loader the class loader used to load this class.
983      * @see ClassPool#toClass(CtClass,java.lang.ClassLoader)
984      */

985     public Class JavaDoc toClass(ClassLoader JavaDoc loader)
986         throws CannotCompileException
987     {
988         return getClassPool().toClass(this, loader);
989     }
990
991     /**
992      * Removes this <code>CtClass</code> object from the
993      * <code>ClassPool</code>.
994      * After this method is called, any method cannot be called on the
995      * removed <code>CtClass</code> object.
996      *
997      * <p>If <code>get()</code> in <code>ClassPool</code> is called
998      * with the name of the removed method,
999      * the <code>ClassPool</code> will read the class file again
1000     * and constructs another <code>CtClass</code> object representing
1001     * the same class.
1002     */

1003    public void detach() {
1004        ClassPool cp = getClassPool();
1005        CtClass obj = cp.removeCached(getName());
1006        if (obj != this)
1007            cp.cacheCtClass(getName(), obj);
1008    }
1009
1010    /**
1011     * Converts this class to a class file.
1012     * Once this method is called, further modifications are not
1013     * possible any more.
1014     *
1015     * @return the contents of the class file.
1016     */

1017    public byte[] toBytecode() throws IOException JavaDoc, CannotCompileException {
1018        ByteArrayOutputStream JavaDoc barray = new ByteArrayOutputStream JavaDoc();
1019        DataOutputStream JavaDoc out = new DataOutputStream JavaDoc(barray);
1020        try {
1021            toBytecode(out);
1022        }
1023        finally {
1024            out.close();
1025        }
1026
1027        return barray.toByteArray();
1028    }
1029
1030    /**
1031     * Writes a class file represented by this <code>CtClass</code>
1032     * object in the current directory.
1033     * Once this method is called, further modifications are not
1034     * possible any more.
1035     */

1036    public void writeFile()
1037        throws NotFoundException, IOException JavaDoc, CannotCompileException
1038    {
1039        writeFile(".");
1040    }
1041
1042    /**
1043     * Writes a class file represented by this <code>CtClass</code>
1044     * object on a local disk.
1045     * Once this method is called, further modifications are not
1046     * possible any more.
1047     *
1048     * @param directoryName it must end without a directory separator.
1049     */

1050    public void writeFile(String JavaDoc directoryName)
1051        throws NotFoundException, CannotCompileException, IOException JavaDoc
1052    {
1053        String JavaDoc classname = getName();
1054        String JavaDoc filename = directoryName + File.separatorChar
1055            + classname.replace('.', File.separatorChar) + ".class";
1056        int pos = filename.lastIndexOf(File.separatorChar);
1057        if (pos > 0) {
1058            String JavaDoc dir = filename.substring(0, pos);
1059            if (!dir.equals("."))
1060                new File(dir).mkdirs();
1061        }
1062
1063        DataOutputStream JavaDoc out
1064            = new DataOutputStream JavaDoc(new BufferedOutputStream JavaDoc(
1065                                new DelayedFileOutputStream(filename)));
1066        try {
1067            toBytecode(out);
1068        }
1069        finally {
1070            out.close();
1071        }
1072    }
1073
1074    static class DelayedFileOutputStream extends OutputStream JavaDoc {
1075        private FileOutputStream JavaDoc file;
1076        private String JavaDoc filename;
1077
1078        DelayedFileOutputStream(String JavaDoc name) {
1079            file = null;
1080            filename = name;
1081        }
1082
1083        private void init() throws IOException JavaDoc {
1084            if (file == null)
1085                file = new FileOutputStream JavaDoc(filename);
1086        }
1087
1088        public void write(int b) throws IOException JavaDoc {
1089            init();
1090            file.write(b);
1091        }
1092
1093        public void write(byte[] b) throws IOException JavaDoc {
1094            init();
1095            file.write(b);
1096        }
1097
1098        public void write(byte[] b, int off, int len) throws IOException JavaDoc {
1099            init();
1100            file.write(b, off, len);
1101
1102        }
1103
1104        public void flush() throws IOException JavaDoc {
1105            init();
1106            file.flush();
1107        }
1108
1109        public void close() throws IOException JavaDoc {
1110            init();
1111            file.close();
1112        }
1113    }
1114
1115    /**
1116     * Converts this class to a class file.
1117     * Once this method is called, further modifications are not
1118     * possible any more.
1119     *
1120     * <p>This method dose not close the output stream in the end.
1121     *
1122     * @param out the output stream that a class file is written to.
1123     */

1124    public void toBytecode(DataOutputStream JavaDoc out)
1125        throws CannotCompileException, IOException JavaDoc
1126    {
1127        throw new CannotCompileException("not a class");
1128    }
1129}
1130
Popular Tags