KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javassist > CtField


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.*;
19 import javassist.compiler.Javac;
20 import javassist.compiler.CompileError;
21 import javassist.compiler.ast.ASTree;
22
23 /**
24  * An instance of CtField represents a field.
25  *
26  * @see CtClass#getDeclaredFields()
27  */

28 public class CtField extends CtMember {
29     protected FieldInfo fieldInfo;
30
31     /**
32      * Creates a <code>CtField</code> object.
33      * The created field must be added to a class
34      * with <code>CtClass.addField()</code>.
35      * An initial value of the field is specified
36      * by a <code>CtField.Initializer</code> object.
37      *
38      * <p>If getter and setter methods are needed,
39      * call <code>CtNewMethod.getter()</code> and
40      * <code>CtNewMethod.setter()</code>.
41      *
42      * @param type field type
43      * @param name field name
44      * @param declaring the class to which the field will be added.
45      *
46      * @see CtClass#addField(CtField)
47      * @see CtNewMethod#getter(String,CtField)
48      * @see CtNewMethod#setter(String,CtField)
49      * @see CtField.Initializer
50      */

51     public CtField(CtClass type, String JavaDoc name, CtClass declaring)
52         throws CannotCompileException
53     {
54         this(Descriptor.of(type), name, declaring);
55     }
56
57     /**
58      * Creates a copy of the given field.
59      * The created field must be added to a class
60      * with <code>CtClass.addField()</code>.
61      * An initial value of the field is specified
62      * by a <code>CtField.Initializer</code> object.
63      *
64      * <p>If getter and setter methods are needed,
65      * call <code>CtNewMethod.getter()</code> and
66      * <code>CtNewMethod.setter()</code>.
67      *
68      * @param src the original field
69      * @param declaring the class to which the field will be added.
70      * @see CtNewMethod#getter(String,CtField)
71      * @see CtNewMethod#setter(String,CtField)
72      * @see CtField.Initializer
73      */

74     public CtField(CtField src, CtClass declaring)
75         throws CannotCompileException
76     {
77         this(src.fieldInfo.getDescriptor(), src.fieldInfo.getName(),
78              declaring);
79     }
80
81     private CtField(String JavaDoc typeDesc, String JavaDoc name, CtClass clazz)
82         throws CannotCompileException
83     {
84         super(clazz);
85         next = null;
86         ClassFile cf = clazz.getClassFile2();
87         if (cf == null)
88             throw new CannotCompileException("bad declaring class: "
89                                              + clazz.getName());
90
91         fieldInfo = new FieldInfo(cf.getConstPool(), name, typeDesc);
92     }
93
94     CtField(FieldInfo fi, CtClass clazz) {
95         super(clazz);
96         fieldInfo = fi;
97         next = null;
98     }
99
100     /**
101      * Returns a String representation of the object.
102      */

103     public String JavaDoc toString() {
104         return getDeclaringClass().getName() + "." + getName()
105                + ":" + fieldInfo.getDescriptor();
106     }
107
108     protected void extendToString(StringBuffer JavaDoc buffer) {
109         buffer.append(' ');
110         buffer.append(getName());
111         buffer.append(' ');
112         buffer.append(fieldInfo.getDescriptor());
113     }
114
115     /* Javac.CtFieldWithInit overrides.
116      */

117     protected ASTree getInitAST() { return null; }
118
119     /* Called by CtClassType.addField().
120      */

121     Initializer getInit() {
122         ASTree tree = getInitAST();
123         if (tree == null)
124             return null;
125         else
126             return Initializer.byExpr(tree);
127     }
128
129     /**
130      * Compiles the given source code and creates a field.
131      * Examples of the source code are:
132      *
133      * <ul><pre>
134      * "public String name;"
135      * "public int k = 3;"</pre></ul>
136      *
137      * <p>Note that the source code ends with <code>';'</code>
138      * (semicolon).
139      *
140      * @param src the source text.
141      * @param declaring the class to which the created field is added.
142      */

143     public static CtField make(String JavaDoc src, CtClass declaring)
144         throws CannotCompileException
145     {
146         Javac compiler = new Javac(declaring);
147         try {
148             CtMember obj = compiler.compile(src);
149             if (obj instanceof CtField)
150                 return (CtField)obj; // an instance of Javac.CtFieldWithInit
151
}
152         catch (CompileError e) {
153             throw new CannotCompileException(e);
154         }
155
156         throw new CannotCompileException("not a field");
157     }
158
159     /**
160      * Returns the FieldInfo representing the field in the class file.
161      */

162     public FieldInfo getFieldInfo() {
163         declaringClass.checkModify();
164         return fieldInfo;
165     }
166
167     /**
168      * Undocumented method. Do not use; internal-use only.
169      */

170     public FieldInfo getFieldInfo2() { return fieldInfo; }
171
172     /**
173      * Returns the class declaring the field.
174      */

175     public CtClass getDeclaringClass() {
176         // this is redundant but for javadoc.
177
return super.getDeclaringClass();
178     }
179
180     /**
181      * Returns the name of the field.
182      */

183     public String JavaDoc getName() {
184         return fieldInfo.getName();
185     }
186
187     /**
188      * Changes the name of the field.
189      */

190     public void setName(String JavaDoc newName) {
191         declaringClass.checkModify();
192         fieldInfo.setName(newName);
193     }
194
195     /**
196      * Returns the encoded modifiers of the field.
197      *
198      * @see Modifier
199      */

200     public int getModifiers() {
201         return AccessFlag.toModifier(fieldInfo.getAccessFlags());
202     }
203
204     /**
205      * Sets the encoded modifiers of the field.
206      *
207      * @see Modifier
208      */

209     public void setModifiers(int mod) {
210         declaringClass.checkModify();
211         fieldInfo.setAccessFlags(AccessFlag.of(mod));
212     }
213
214     /**
215      * Returns the type of the field.
216      */

217     public CtClass getType() throws NotFoundException {
218         return Descriptor.toCtClass(fieldInfo.getDescriptor(),
219                                     declaringClass.getClassPool());
220     }
221
222     /**
223      * Sets the type of the field.
224      */

225     public void setType(CtClass clazz) {
226         declaringClass.checkModify();
227         fieldInfo.setDescriptor(Descriptor.of(clazz));
228     }
229
230     /**
231      * Returns the value of this field if it is a constant field.
232      * This method works only if the field type is a primitive type
233      * or <code>String</code> type. Otherwise, it returns <code>null</code>.
234      * A constant field is <code>static</code> and <code>final</code>.
235      *
236      * @return a <code>Integer</code>, <code>Long</code>, <code>Float</code>,
237      * <code>Double</code>, <code>Boolean</code>,
238      * or <code>String</code> object
239      * representing the constant value.
240      * <code>null</code> if it is not a constant field
241      * or if the field type is not a primitive type
242      * or <code>String</code>.
243      */

244     public Object JavaDoc getConstantValue() {
245         // When this method is modified,
246
// see also getConstantFieldValue() in TypeChecker.
247

248         int index = fieldInfo.getConstantValue();
249         if (index == 0)
250             return null;
251
252         ConstPool cp = fieldInfo.getConstPool();
253         switch (cp.getTag(index)) {
254             case ConstPool.CONST_Long :
255                 return new Long JavaDoc(cp.getLongInfo(index));
256             case ConstPool.CONST_Float :
257                 return new Float JavaDoc(cp.getFloatInfo(index));
258             case ConstPool.CONST_Double :
259                 return new Double JavaDoc(cp.getDoubleInfo(index));
260             case ConstPool.CONST_Integer :
261                 int value = cp.getIntegerInfo(index);
262                 // "Z" means boolean type.
263
if ("Z".equals(fieldInfo.getDescriptor()))
264                     return new Boolean JavaDoc(value != 0);
265                 else
266                     return new Integer JavaDoc(value);
267             case ConstPool.CONST_String :
268                 return cp.getStringInfo(index);
269             default :
270                 throw new RuntimeException JavaDoc("bad tag: " + cp.getTag(index)
271                                            + " at " + index);
272         }
273     }
274
275     /**
276      * Obtains an attribute with the given name.
277      * If that attribute is not found in the class file, this
278      * method returns null.
279      *
280      * @param name attribute name
281      */

282     public byte[] getAttribute(String JavaDoc name) {
283         AttributeInfo ai = fieldInfo.getAttribute(name);
284         if (ai == null)
285             return null;
286         else
287             return ai.get();
288     }
289
290     /**
291      * Adds an attribute. The attribute is saved in the class file.
292      *
293      * @param name attribute name
294      * @param data attribute value
295      */

296     public void setAttribute(String JavaDoc name, byte[] data) {
297         declaringClass.checkModify();
298         fieldInfo.addAttribute(new AttributeInfo(fieldInfo.getConstPool(),
299                                                  name, data));
300     }
301
302     // inner classes
303

304     /**
305      * Instances of this class specify how to initialize a field.
306      * <code>Initializer</code> is passed to
307      * <code>CtClass.addField()</code> with a <code>CtField</code>.
308      *
309      * <p>This class cannot be instantiated with the <code>new</code> operator.
310      * Factory methods such as <code>byParameter()</code> and
311      * <code>byNew</code>
312      * must be used for the instantiation. They create a new instance with
313      * the given parameters and return it.
314      *
315      * @see CtClass#addField(CtField,CtField.Initializer)
316      */

317     public static abstract class Initializer {
318         /**
319          * Makes an initializer that assigns a constant integer value.
320          * The field must be integer type.
321          */

322         public static Initializer constant(int i) {
323             return new IntInitializer(i);
324         }
325
326         /**
327          * Makes an initializer that assigns a constant long value.
328          * The field must be long type.
329          */

330         public static Initializer constant(long l) {
331             return new LongInitializer(l);
332         }
333
334         /**
335          * Makes an initializer that assigns a constant double value.
336          * The field must be double type.
337          */

338         public static Initializer constant(double d) {
339             return new DoubleInitializer(d);
340         }
341
342         /**
343          * Makes an initializer that assigns a constant string value.
344          * The field must be <code>java.lang.String</code> type.
345          */

346         public static Initializer constant(String JavaDoc s) {
347             return new StringInitializer(s);
348         }
349
350         /**
351          * Makes an initializer using a constructor parameter.
352          *
353          * <p>The initial value is the
354          * N-th parameter given to the constructor of the object including
355          * the field. If the constructor takes less than N parameters,
356          * the field is not initialized.
357          * If the field is static, it is never initialized.
358          *
359          * @param nth the n-th (&gt;= 0) parameter is used as
360          * the initial value.
361          * If nth is 0, then the first parameter is
362          * used.
363          */

364         public static Initializer byParameter(int nth) {
365             ParamInitializer i = new ParamInitializer();
366             i.nthParam = nth;
367             return i;
368         }
369
370         /**
371          * Makes an initializer creating a new object.
372          *
373          * <p>This initializer creates a new object and uses it as the initial
374          * value of the field. The constructor of the created object receives
375          * the parameter:
376          *
377          * <ul><code>Object obj</code> - the object including the field.<br>
378          * </ul>
379          *
380          * <p>If the initialized field is static, then the constructor does
381          * not receive any parameters.
382          *
383          * @param objectType the class instantiated for the initial value.
384          */

385         public static Initializer byNew(CtClass objectType) {
386             NewInitializer i = new NewInitializer();
387             i.objectType = objectType;
388             i.stringParams = null;
389             i.withConstructorParams = false;
390             return i;
391         }
392
393         /**
394          * Makes an initializer creating a new object.
395          *
396          * <p>This initializer creates a new object and uses it as the initial
397          * value of the field. The constructor of the created object receives
398          * the parameters:
399          *
400          * <ul><code>Object obj</code> - the object including the field.<br>
401          * <code>String[] strs</code> - the character strings specified
402          * by <code>stringParams</code><br>
403          * </ul>
404          *
405          * <p>If the initialized field is static, then the constructor
406          * receives only <code>strs</code>.
407          *
408          * @param objectType the class instantiated for the initial value.
409          * @param stringParams the array of strings passed to the
410          * constructor.
411          */

412         public static Initializer byNew(CtClass objectType,
413                                              String JavaDoc[] stringParams) {
414             NewInitializer i = new NewInitializer();
415             i.objectType = objectType;
416             i.stringParams = stringParams;
417             i.withConstructorParams = false;
418             return i;
419         }
420
421         /**
422          * Makes an initializer creating a new object.
423          *
424          * <p>This initializer creates a new object and uses it as the initial
425          * value of the field. The constructor of the created object receives
426          * the parameters:
427          *
428          * <ul><code>Object obj</code> - the object including the field.<br>
429          * <code>Object[] args</code> - the parameters passed to the
430          * constructor of the object including the
431          * filed.
432          * </ul>
433          *
434          * <p>If the initialized field is static, then the constructor does
435          * not receive any parameters.
436          *
437          * @param objectType the class instantiated for the initial value.
438          *
439          * @see javassist.CtField.Initializer#byNewArray(CtClass,int)
440          * @see javassist.CtField.Initializer#byNewArray(CtClass,int[])
441          */

442         public static Initializer byNewWithParams(CtClass objectType) {
443             NewInitializer i = new NewInitializer();
444             i.objectType = objectType;
445             i.stringParams = null;
446             i.withConstructorParams = true;
447             return i;
448         }
449
450         /**
451          * Makes an initializer creating a new object.
452          *
453          * <p>This initializer creates a new object and uses it as the initial
454          * value of the field. The constructor of the created object receives
455          * the parameters:
456          *
457          * <ul><code>Object obj</code> - the object including the field.<br>
458          * <code>String[] strs</code> - the character strings specified
459          * by <code>stringParams</code><br>
460          * <code>Object[] args</code> - the parameters passed to the
461          * constructor of the object including the
462          * filed.
463          * </ul>
464          *
465          * <p>If the initialized field is static, then the constructor receives
466          * only <code>strs</code>.
467          *
468          * @param objectType the class instantiated for the initial value.
469          * @param stringParams the array of strings passed to the
470          * constructor.
471          */

472         public static Initializer byNewWithParams(CtClass objectType,
473                                                String JavaDoc[] stringParams) {
474             NewInitializer i = new NewInitializer();
475             i.objectType = objectType;
476             i.stringParams = stringParams;
477             i.withConstructorParams = true;
478             return i;
479         }
480
481         /**
482          * Makes an initializer calling a static method.
483          *
484          * <p>This initializer calls a static method and uses the returned
485          * value as the initial value of the field.
486          * The called method receives the parameters:
487          *
488          * <ul><code>Object obj</code> - the object including the field.<br>
489          * </ul>
490          *
491          * <p>If the initialized field is static, then the method does
492          * not receive any parameters.
493          *
494          * <p>The type of the returned value must be the same as the field
495          * type.
496          *
497          * @param methodClass the class that the static method is
498          * declared in.
499          * @param methodName the name of the satic method.
500          */

501         public static Initializer byCall(CtClass methodClass,
502                                               String JavaDoc methodName) {
503             MethodInitializer i = new MethodInitializer();
504             i.objectType = methodClass;
505             i.methodName = methodName;
506             i.stringParams = null;
507             i.withConstructorParams = false;
508             return i;
509         }
510
511         /**
512          * Makes an initializer calling a static method.
513          *
514          * <p>This initializer calls a static method and uses the returned
515          * value as the initial value of the field. The called method
516          * receives the parameters:
517          *
518          * <ul><code>Object obj</code> - the object including the field.<br>
519          * <code>String[] strs</code> - the character strings specified
520          * by <code>stringParams</code><br>
521          * </ul>
522          *
523          * <p>If the initialized field is static, then the method
524          * receive only <code>strs</code>.
525          *
526          * <p>The type of the returned value must be the same as the field
527          * type.
528          *
529          * @param methodClass the class that the static method is
530          * declared in.
531          * @param methodName the name of the satic method.
532          * @param stringParams the array of strings passed to the
533          * static method.
534          */

535         public static Initializer byCall(CtClass methodClass,
536                                               String JavaDoc methodName,
537                                               String JavaDoc[] stringParams) {
538             MethodInitializer i = new MethodInitializer();
539             i.objectType = methodClass;
540             i.methodName = methodName;
541             i.stringParams = stringParams;
542             i.withConstructorParams = false;
543             return i;
544         }
545
546         /**
547          * Makes an initializer calling a static method.
548          *
549          * <p>This initializer calls a static method and uses the returned
550          * value as the initial value of the field. The called method
551          * receives the parameters:
552          *
553          * <ul><code>Object obj</code> - the object including the field.<br>
554          * <code>Object[] args</code> - the parameters passed to the
555          * constructor of the object including the
556          * filed.
557          * </ul>
558          *
559          * <p>If the initialized field is static, then the method does
560          * not receive any parameters.
561          *
562          * <p>The type of the returned value must be the same as the field
563          * type.
564          *
565          * @param methodClass the class that the static method is
566          * declared in.
567          * @param methodName the name of the satic method.
568          */

569         public static Initializer byCallWithParams(CtClass methodClass,
570                                                         String JavaDoc methodName) {
571             MethodInitializer i = new MethodInitializer();
572             i.objectType = methodClass;
573             i.methodName = methodName;
574             i.stringParams = null;
575             i.withConstructorParams = true;
576             return i;
577         }
578
579         /**
580          * Makes an initializer calling a static method.
581          *
582          * <p>This initializer calls a static method and uses the returned
583          * value as the initial value of the field. The called method
584          * receives the parameters:
585          *
586          * <ul><code>Object obj</code> - the object including the field.<br>
587          * <code>String[] strs</code> - the character strings specified
588          * by <code>stringParams</code><br>
589          * <code>Object[] args</code> - the parameters passed to the
590          * constructor of the object including the
591          * filed.
592          * </ul>
593          *
594          * <p>If the initialized field is static, then the method
595          * receive only <code>strs</code>.
596          *
597          * <p>The type of the returned value must be the same as the field
598          * type.
599          *
600          * @param methodClass the class that the static method is
601          * declared in.
602          * @param methodName the name of the satic method.
603          * @param stringParams the array of strings passed to the
604          * static method.
605          */

606         public static Initializer byCallWithParams(CtClass methodClass,
607                                 String JavaDoc methodName, String JavaDoc[] stringParams) {
608             MethodInitializer i = new MethodInitializer();
609             i.objectType = methodClass;
610             i.methodName = methodName;
611             i.stringParams = stringParams;
612             i.withConstructorParams = true;
613             return i;
614         }
615
616         /**
617          * Makes an initializer creating a new array.
618          *
619          * @param type the type of the array.
620          * @param size the size of the array.
621          * @throws NotFoundException if the type of the array components
622          * is not found.
623          */

624         public static Initializer byNewArray(CtClass type, int size)
625             throws NotFoundException
626         {
627             return new ArrayInitializer(type.getComponentType(), size);
628         }
629
630         /**
631          * Makes an initializer creating a new multi-dimensional array.
632          *
633          * @param type the type of the array.
634          * @param sizes an <code>int</code> array of the size in every
635          * dimension.
636          * The first element is the size in the first
637          * dimension. The second is in the second, etc.
638          */

639         public static Initializer byNewArray(CtClass type, int[] sizes) {
640             return new MultiArrayInitializer(type, sizes);
641         }
642
643         /**
644          * Makes an initializer.
645          *
646          * @param source initializer expression.
647          */

648         public static Initializer byExpr(String JavaDoc source) {
649             return new CodeInitializer(source);
650         }
651
652         static Initializer byExpr(ASTree source) {
653             return new PtreeInitializer(source);
654         }
655
656         // Check whether this initializer is valid for the field type.
657
// If it is invaild, this method throws an exception.
658
void check(CtClass type) throws CannotCompileException {}
659
660         // produce codes for initialization
661
abstract int compile(CtClass type, String JavaDoc name, Bytecode code,
662                              CtClass[] parameters, Javac drv)
663             throws CannotCompileException;
664
665         // produce codes for initialization
666
abstract int compileIfStatic(CtClass type, String JavaDoc name,
667                 Bytecode code, Javac drv) throws CannotCompileException;
668     }
669
670     static abstract class CodeInitializer0 extends Initializer {
671         abstract void compileExpr(Javac drv) throws CompileError;
672
673         int compile(CtClass type, String JavaDoc name, Bytecode code,
674                     CtClass[] parameters, Javac drv)
675             throws CannotCompileException
676         {
677             try {
678                 code.addAload(0);
679                 compileExpr(drv);
680                 code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
681                 return code.getMaxStack();
682             }
683             catch (CompileError e) {
684                 throw new CannotCompileException(e);
685             }
686         }
687
688         int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
689                             Javac drv) throws CannotCompileException
690         {
691             try {
692                 compileExpr(drv);
693                 code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
694                 return code.getMaxStack();
695             }
696             catch (CompileError e) {
697                 throw new CannotCompileException(e);
698             }
699         }
700     }
701
702     static class CodeInitializer extends CodeInitializer0 {
703         private String JavaDoc expression;
704
705         CodeInitializer(String JavaDoc expr) { expression = expr; }
706
707         void compileExpr(Javac drv) throws CompileError {
708             drv.compileExpr(expression);
709         }
710     }
711
712     static class PtreeInitializer extends CodeInitializer0 {
713         private ASTree expression;
714
715         PtreeInitializer(ASTree expr) { expression = expr; }
716
717         void compileExpr(Javac drv) throws CompileError {
718             drv.compileExpr(expression);
719         }
720     }
721
722     /**
723      * A field initialized with a parameter passed to the constructor
724      * of the class containing that field.
725      */

726     static class ParamInitializer extends Initializer {
727         int nthParam;
728
729         ParamInitializer() {}
730
731         int compile(CtClass type, String JavaDoc name, Bytecode code,
732                     CtClass[] parameters, Javac drv)
733             throws CannotCompileException
734         {
735             if (parameters != null && nthParam < parameters.length) {
736                 code.addAload(0);
737                 int nth = nthParamToLocal(nthParam, parameters, false);
738                 int s = code.addLoad(nth, type) + 1;
739                 code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
740                 return s; // stack size
741
}
742             else
743                 return 0; // do not initialize
744
}
745
746         /**
747          * Computes the index of the local variable that the n-th parameter
748          * is assigned to.
749          *
750          * @param nth n-th parameter
751          * @param params list of parameter types
752          * @param isStatic true if the method is static.
753          */

754         static int nthParamToLocal(int nth, CtClass[] params,
755                                    boolean isStatic) {
756             CtClass longType = CtClass.longType;
757             CtClass doubleType = CtClass.doubleType;
758             int k;
759             if (isStatic)
760                 k = 0;
761             else
762                 k = 1; // 0 is THIS.
763

764             for (int i = 0; i < nth; ++i) {
765                 CtClass type = params[i];
766                 if (type == longType || type == doubleType)
767                     k += 2;
768                 else
769                     ++k;
770             }
771
772             return k;
773         }
774
775         int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
776                             Javac drv) throws CannotCompileException
777         {
778             return 0;
779         }
780     }
781
782     /**
783      * A field initialized with an object created by the new operator.
784      */

785     static class NewInitializer extends Initializer {
786         CtClass objectType;
787         String JavaDoc[] stringParams;
788         boolean withConstructorParams;
789
790         NewInitializer() {}
791
792         /**
793          * Produces codes in which a new object is created and assigned to
794          * the field as the initial value.
795          */

796         int compile(CtClass type, String JavaDoc name, Bytecode code,
797                     CtClass[] parameters, Javac drv)
798             throws CannotCompileException
799         {
800             int stacksize;
801
802             code.addAload(0);
803             code.addNew(objectType);
804             code.add(Bytecode.DUP);
805             code.addAload(0);
806
807             if (stringParams == null)
808                 stacksize = 4;
809             else
810                 stacksize = compileStringParameter(code) + 4;
811
812             if (withConstructorParams)
813                 stacksize += CtNewWrappedMethod.compileParameterList(code,
814                                                             parameters, 1);
815
816             code.addInvokespecial(objectType, "<init>", getDescriptor());
817             code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
818             return stacksize;
819         }
820
821         private String JavaDoc getDescriptor() {
822             final String JavaDoc desc3
823         = "(Ljava/lang/Object;[Ljava/lang/String;[Ljava/lang/Object;)V";
824
825             if (stringParams == null)
826                 if (withConstructorParams)
827                     return "(Ljava/lang/Object;[Ljava/lang/Object;)V";
828                 else
829                     return "(Ljava/lang/Object;)V";
830             else
831                 if (withConstructorParams)
832                     return desc3;
833                 else
834                     return "(Ljava/lang/Object;[Ljava/lang/String;)V";
835         }
836
837         /**
838          * Produces codes for a static field.
839          */

840         int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
841                             Javac drv) throws CannotCompileException
842         {
843             String JavaDoc desc;
844
845             code.addNew(objectType);
846             code.add(Bytecode.DUP);
847
848             int stacksize = 2;
849             if (stringParams == null)
850                 desc = "()V";
851             else {
852                 desc = "([Ljava/lang/String;)V";
853                 stacksize += compileStringParameter(code);
854             }
855
856             code.addInvokespecial(objectType, "<init>", desc);
857             code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
858             return stacksize;
859         }
860
861         protected final int compileStringParameter(Bytecode code)
862             throws CannotCompileException
863         {
864             int nparam = stringParams.length;
865             code.addIconst(nparam);
866             code.addAnewarray("java.lang.String");
867             for (int j = 0; j < nparam; ++j) {
868                 code.add(Bytecode.DUP); // dup
869
code.addIconst(j); // iconst_<j>
870
code.addLdc(stringParams[j]); // ldc ...
871
code.add(Bytecode.AASTORE); // aastore
872
}
873
874             return 4;
875         }
876
877     }
878
879     /**
880      * A field initialized with the result of a static method call.
881      */

882     static class MethodInitializer extends NewInitializer {
883         String JavaDoc methodName;
884         // the method class is specified by objectType.
885

886         MethodInitializer() {}
887
888         /**
889          * Produces codes in which a new object is created and assigned to
890          * the field as the initial value.
891          */

892         int compile(CtClass type, String JavaDoc name, Bytecode code,
893                     CtClass[] parameters, Javac drv)
894             throws CannotCompileException
895         {
896             int stacksize;
897
898             code.addAload(0);
899             code.addAload(0);
900
901             if (stringParams == null)
902                 stacksize = 2;
903             else
904                 stacksize = compileStringParameter(code) + 2;
905
906             if (withConstructorParams)
907                 stacksize += CtNewWrappedMethod.compileParameterList(code,
908                                                             parameters, 1);
909
910             String JavaDoc typeDesc = Descriptor.of(type);
911             String JavaDoc mDesc = getDescriptor() + typeDesc;
912             code.addInvokestatic(objectType, methodName, mDesc);
913             code.addPutfield(Bytecode.THIS, name, typeDesc);
914             return stacksize;
915         }
916
917         private String JavaDoc getDescriptor() {
918             final String JavaDoc desc3
919                 = "(Ljava/lang/Object;[Ljava/lang/String;[Ljava/lang/Object;)";
920
921             if (stringParams == null)
922                 if (withConstructorParams)
923                     return "(Ljava/lang/Object;[Ljava/lang/Object;)";
924                 else
925                     return "(Ljava/lang/Object;)";
926             else
927                 if (withConstructorParams)
928                     return desc3;
929                 else
930                     return "(Ljava/lang/Object;[Ljava/lang/String;)";
931         }
932
933         /**
934          * Produces codes for a static field.
935          */

936         int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
937                             Javac drv) throws CannotCompileException
938         {
939             String JavaDoc desc;
940
941             int stacksize = 1;
942             if (stringParams == null)
943                 desc = "()";
944             else {
945                 desc = "([Ljava/lang/String;)";
946                 stacksize += compileStringParameter(code);
947             }
948
949             String JavaDoc typeDesc = Descriptor.of(type);
950             code.addInvokestatic(objectType, methodName, desc + typeDesc);
951             code.addPutstatic(Bytecode.THIS, name, typeDesc);
952             return stacksize;
953         }
954     }
955
956     static class IntInitializer extends Initializer {
957         int value;
958
959         IntInitializer(int v) { value = v; }
960
961         void check(CtClass type) throws CannotCompileException {
962             if (type != CtClass.intType)
963                 throw new CannotCompileException("type mismatch");
964         }
965
966         int compile(CtClass type, String JavaDoc name, Bytecode code,
967                     CtClass[] parameters, Javac drv)
968             throws CannotCompileException
969         {
970             code.addAload(0);
971             code.addIconst(value);
972             code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
973             return 2; // stack size
974
}
975
976         int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
977                             Javac drv) throws CannotCompileException
978         {
979             code.addIconst(value);
980             code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
981             return 1; // stack size
982
}
983     }
984
985     static class LongInitializer extends Initializer {
986         long value;
987
988         LongInitializer(long v) { value = v; }
989
990         void check(CtClass type) throws CannotCompileException {
991             if (type != CtClass.longType)
992                 throw new CannotCompileException("type mismatch");
993         }
994
995         int compile(CtClass type, String JavaDoc name, Bytecode code,
996                     CtClass[] parameters, Javac drv)
997             throws CannotCompileException
998         {
999             code.addAload(0);
1000            code.addLdc2w(value);
1001            code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
1002            return 3; // stack size
1003
}
1004
1005        int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
1006                            Javac drv) throws CannotCompileException
1007        {
1008            code.addLdc2w(value);
1009            code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
1010            return 2; // stack size
1011
}
1012    }
1013
1014    static class DoubleInitializer extends Initializer {
1015        double value;
1016
1017        DoubleInitializer(double v) { value = v; }
1018
1019        void check(CtClass type) throws CannotCompileException {
1020            if (type != CtClass.doubleType)
1021                throw new CannotCompileException("type mismatch");
1022        }
1023
1024        int compile(CtClass type, String JavaDoc name, Bytecode code,
1025                    CtClass[] parameters, Javac drv)
1026            throws CannotCompileException
1027        {
1028            code.addAload(0);
1029            code.addLdc2w(value);
1030            code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
1031            return 3; // stack size
1032
}
1033
1034        int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
1035                            Javac drv) throws CannotCompileException
1036        {
1037            code.addLdc2w(value);
1038            code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
1039            return 2; // stack size
1040
}
1041    }
1042
1043    static class StringInitializer extends Initializer {
1044        String JavaDoc value;
1045
1046        StringInitializer(String JavaDoc v) { value = v; }
1047
1048        void check(CtClass type) throws CannotCompileException {
1049            if (!type.getName().equals("java.lang.String"))
1050                throw new CannotCompileException("type mismatch");
1051        }
1052
1053        int compile(CtClass type, String JavaDoc name, Bytecode code,
1054                    CtClass[] parameters, Javac drv)
1055            throws CannotCompileException
1056        {
1057            code.addAload(0);
1058            code.addLdc(value);
1059            code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
1060            return 2; // stack size
1061
}
1062
1063        int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
1064                            Javac drv) throws CannotCompileException
1065        {
1066            code.addLdc(value);
1067            code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
1068            return 1; // stack size
1069
}
1070    }
1071
1072    static class ArrayInitializer extends Initializer {
1073        CtClass type;
1074        int size;
1075
1076        ArrayInitializer(CtClass t, int s) { type = t; size = s; }
1077
1078        private void addNewarray(Bytecode code) {
1079            if (type.isPrimitive())
1080                code.addNewarray(((CtPrimitiveType)type).getArrayType(),
1081                                 size);
1082            else
1083                code.addAnewarray(type, size);
1084        }
1085
1086        int compile(CtClass type, String JavaDoc name, Bytecode code,
1087                    CtClass[] parameters, Javac drv)
1088            throws CannotCompileException
1089        {
1090            code.addAload(0);
1091            addNewarray(code);
1092            code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
1093            return 2; // stack size
1094
}
1095
1096        int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
1097                            Javac drv) throws CannotCompileException
1098        {
1099            addNewarray(code);
1100            code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
1101            return 1; // stack size
1102
}
1103    }
1104
1105    static class MultiArrayInitializer extends Initializer {
1106        CtClass type;
1107        int[] dim;
1108
1109        MultiArrayInitializer(CtClass t, int[] d) { type = t; dim = d; }
1110
1111        void check(CtClass type) throws CannotCompileException {
1112            if (!type.isArray())
1113                throw new CannotCompileException("type mismatch");
1114        }
1115
1116        int compile(CtClass type, String JavaDoc name, Bytecode code,
1117                    CtClass[] parameters, Javac drv)
1118            throws CannotCompileException
1119        {
1120            code.addAload(0);
1121            int s = code.addMultiNewarray(type, dim);
1122            code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
1123            return s + 1; // stack size
1124
}
1125
1126        int compileIfStatic(CtClass type, String JavaDoc name, Bytecode code,
1127                            Javac drv) throws CannotCompileException
1128        {
1129            int s = code.addMultiNewarray(type, dim);
1130            code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
1131            return s; // stack size
1132
}
1133    }
1134}
1135
Popular Tags