You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- 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. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist;
  17. import java.util.List;
  18. import javassist.bytecode.AccessFlag;
  19. import javassist.bytecode.AnnotationsAttribute;
  20. import javassist.bytecode.AttributeInfo;
  21. import javassist.bytecode.Bytecode;
  22. import javassist.bytecode.ClassFile;
  23. import javassist.bytecode.ConstPool;
  24. import javassist.bytecode.Descriptor;
  25. import javassist.bytecode.FieldInfo;
  26. import javassist.bytecode.SignatureAttribute;
  27. import javassist.compiler.CompileError;
  28. import javassist.compiler.Javac;
  29. import javassist.compiler.SymbolTable;
  30. import javassist.compiler.ast.ASTree;
  31. import javassist.compiler.ast.DoubleConst;
  32. import javassist.compiler.ast.IntConst;
  33. import javassist.compiler.ast.StringL;
  34. /**
  35. * An instance of CtField represents a field.
  36. *
  37. * @see CtClass#getDeclaredFields()
  38. */
  39. public class CtField extends CtMember {
  40. static final String javaLangString = "java.lang.String";
  41. protected FieldInfo fieldInfo;
  42. /**
  43. * Creates a <code>CtField</code> object.
  44. * The created field must be added to a class
  45. * with <code>CtClass.addField()</code>.
  46. * An initial value of the field is specified
  47. * by a <code>CtField.Initializer</code> object.
  48. *
  49. * <p>If getter and setter methods are needed,
  50. * call <code>CtNewMethod.getter()</code> and
  51. * <code>CtNewMethod.setter()</code>.
  52. *
  53. * @param type field type
  54. * @param name field name
  55. * @param declaring the class to which the field will be added.
  56. *
  57. * @see CtClass#addField(CtField)
  58. * @see CtNewMethod#getter(String,CtField)
  59. * @see CtNewMethod#setter(String,CtField)
  60. * @see CtField.Initializer
  61. */
  62. public CtField(CtClass type, String name, CtClass declaring)
  63. throws CannotCompileException
  64. {
  65. this(Descriptor.of(type), name, declaring);
  66. }
  67. /**
  68. * Creates a copy of the given field.
  69. * The created field must be added to a class
  70. * with <code>CtClass.addField()</code>.
  71. * An initial value of the field is specified
  72. * by a <code>CtField.Initializer</code> object.
  73. *
  74. * <p>If getter and setter methods are needed,
  75. * call <code>CtNewMethod.getter()</code> and
  76. * <code>CtNewMethod.setter()</code>.
  77. *
  78. * @param src the original field
  79. * @param declaring the class to which the field will be added.
  80. * @see CtNewMethod#getter(String,CtField)
  81. * @see CtNewMethod#setter(String,CtField)
  82. * @see CtField.Initializer
  83. */
  84. public CtField(CtField src, CtClass declaring)
  85. throws CannotCompileException
  86. {
  87. this(src.fieldInfo.getDescriptor(), src.fieldInfo.getName(),
  88. declaring);
  89. FieldInfo fi = fieldInfo;
  90. fi.setAccessFlags(src.fieldInfo.getAccessFlags());
  91. ConstPool cp = fi.getConstPool();
  92. List<AttributeInfo> attributes = src.fieldInfo.getAttributes();
  93. for (AttributeInfo ainfo : attributes)
  94. fi.addAttribute(ainfo.copy(cp, null));
  95. }
  96. private CtField(String typeDesc, String name, CtClass clazz)
  97. throws CannotCompileException
  98. {
  99. super(clazz);
  100. ClassFile cf = clazz.getClassFile2();
  101. if (cf == null)
  102. throw new CannotCompileException("bad declaring class: "
  103. + clazz.getName());
  104. fieldInfo = new FieldInfo(cf.getConstPool(), name, typeDesc);
  105. }
  106. CtField(FieldInfo fi, CtClass clazz) {
  107. super(clazz);
  108. fieldInfo = fi;
  109. }
  110. /**
  111. * Returns a String representation of the object.
  112. */
  113. @Override
  114. public String toString() {
  115. return getDeclaringClass().getName() + "." + getName()
  116. + ":" + fieldInfo.getDescriptor();
  117. }
  118. @Override
  119. protected void extendToString(StringBuilder buffer) {
  120. buffer.append(' ');
  121. buffer.append(getName());
  122. buffer.append(' ');
  123. buffer.append(fieldInfo.getDescriptor());
  124. }
  125. /* Javac.CtFieldWithInit overrides. */
  126. protected ASTree getInitAST() { return null; }
  127. /* Called by CtClassType.addField(). */
  128. Initializer getInit() {
  129. ASTree tree = getInitAST();
  130. if (tree == null)
  131. return null;
  132. return Initializer.byExpr(tree);
  133. }
  134. /**
  135. * Compiles the given source code and creates a field.
  136. * Examples of the source code are:
  137. *
  138. * <pre>
  139. * "public String name;"
  140. * "public int k = 3;"</pre>
  141. *
  142. * <p>Note that the source code ends with <code>';'</code>
  143. * (semicolon).
  144. *
  145. * @param src the source text.
  146. * @param declaring the class to which the created field is added.
  147. */
  148. public static CtField make(String src, CtClass declaring)
  149. throws CannotCompileException
  150. {
  151. Javac compiler = new Javac(declaring);
  152. try {
  153. CtMember obj = compiler.compile(src);
  154. if (obj instanceof CtField)
  155. return (CtField)obj; // an instance of Javac.CtFieldWithInit
  156. }
  157. catch (CompileError e) {
  158. throw new CannotCompileException(e);
  159. }
  160. throw new CannotCompileException("not a field");
  161. }
  162. /**
  163. * Returns the FieldInfo representing the field in the class file.
  164. */
  165. public FieldInfo getFieldInfo() {
  166. declaringClass.checkModify();
  167. return fieldInfo;
  168. }
  169. /**
  170. * Returns the FieldInfo representing the field in the class
  171. * file (read only).
  172. * Normal applications do not need calling this method. Use
  173. * <code>getFieldInfo()</code>.
  174. *
  175. * <p>The <code>FieldInfo</code> object obtained by this method
  176. * is read only. Changes to this object might not be reflected
  177. * on a class file generated by <code>toBytecode()</code>,
  178. * <code>toClass()</code>, etc in <code>CtClass</code>.
  179. *
  180. * <p>This method is available even if the <code>CtClass</code>
  181. * containing this field is frozen. However, if the class is
  182. * frozen, the <code>FieldInfo</code> might be also pruned.
  183. *
  184. * @see #getFieldInfo()
  185. * @see CtClass#isFrozen()
  186. * @see CtClass#prune()
  187. */
  188. public FieldInfo getFieldInfo2() { return fieldInfo; }
  189. /**
  190. * Returns the class declaring the field.
  191. */
  192. @Override
  193. public CtClass getDeclaringClass() {
  194. // this is redundant but for javadoc.
  195. return super.getDeclaringClass();
  196. }
  197. /**
  198. * Returns the name of the field.
  199. */
  200. @Override
  201. public String getName() {
  202. return fieldInfo.getName();
  203. }
  204. /**
  205. * Changes the name of the field.
  206. */
  207. public void setName(String newName) {
  208. declaringClass.checkModify();
  209. fieldInfo.setName(newName);
  210. }
  211. /**
  212. * Returns the encoded modifiers of the field.
  213. *
  214. * @see Modifier
  215. */
  216. @Override
  217. public int getModifiers() {
  218. return AccessFlag.toModifier(fieldInfo.getAccessFlags());
  219. }
  220. /**
  221. * Sets the encoded modifiers of the field.
  222. *
  223. * @see Modifier
  224. */
  225. @Override
  226. public void setModifiers(int mod) {
  227. declaringClass.checkModify();
  228. fieldInfo.setAccessFlags(AccessFlag.of(mod));
  229. }
  230. /**
  231. * Returns true if the class has the specified annotation type.
  232. *
  233. * @param typeName the name of annotation type.
  234. * @return <code>true</code> if the annotation is found, otherwise <code>false</code>.
  235. * @since 3.21
  236. */
  237. @Override
  238. public boolean hasAnnotation(String typeName) {
  239. FieldInfo fi = getFieldInfo2();
  240. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  241. fi.getAttribute(AnnotationsAttribute.invisibleTag);
  242. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  243. fi.getAttribute(AnnotationsAttribute.visibleTag);
  244. return CtClassType.hasAnnotationType(typeName, getDeclaringClass().getClassPool(),
  245. ainfo, ainfo2);
  246. }
  247. /**
  248. * Returns the annotation if the class has the specified annotation class.
  249. * For example, if an annotation <code>@Author</code> is associated
  250. * with this field, an <code>Author</code> object is returned.
  251. * The member values can be obtained by calling methods on
  252. * the <code>Author</code> object.
  253. *
  254. * @param clz the annotation class.
  255. * @return the annotation if found, otherwise <code>null</code>.
  256. * @since 3.11
  257. */
  258. @Override
  259. public Object getAnnotation(Class<?> clz) throws ClassNotFoundException {
  260. FieldInfo fi = getFieldInfo2();
  261. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  262. fi.getAttribute(AnnotationsAttribute.invisibleTag);
  263. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  264. fi.getAttribute(AnnotationsAttribute.visibleTag);
  265. return CtClassType.getAnnotationType(clz, getDeclaringClass().getClassPool(),
  266. ainfo, ainfo2);
  267. }
  268. /**
  269. * Returns the annotations associated with this field.
  270. *
  271. * @return an array of annotation-type objects.
  272. * @see #getAvailableAnnotations()
  273. * @since 3.1
  274. */
  275. @Override
  276. public Object[] getAnnotations() throws ClassNotFoundException {
  277. return getAnnotations(false);
  278. }
  279. /**
  280. * Returns the annotations associated with this field.
  281. * If any annotations are not on the classpath, they are not included
  282. * in the returned array.
  283. *
  284. * @return an array of annotation-type objects.
  285. * @see #getAnnotations()
  286. * @since 3.3
  287. */
  288. @Override
  289. public Object[] getAvailableAnnotations(){
  290. try {
  291. return getAnnotations(true);
  292. }
  293. catch (ClassNotFoundException e) {
  294. throw new RuntimeException("Unexpected exception", e);
  295. }
  296. }
  297. private Object[] getAnnotations(boolean ignoreNotFound) throws ClassNotFoundException {
  298. FieldInfo fi = getFieldInfo2();
  299. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  300. fi.getAttribute(AnnotationsAttribute.invisibleTag);
  301. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  302. fi.getAttribute(AnnotationsAttribute.visibleTag);
  303. return CtClassType.toAnnotationType(ignoreNotFound, getDeclaringClass().getClassPool(),
  304. ainfo, ainfo2);
  305. }
  306. /**
  307. * Returns the character string representing the type of the field.
  308. * The field signature is represented by a character string
  309. * called a field descriptor, which is defined in the JVM specification.
  310. * If two fields have the same type,
  311. * <code>getSignature()</code> returns the same string.
  312. *
  313. * <p>Note that the returned string is not the type signature
  314. * contained in the <code>SignatureAttirbute</code>. It is
  315. * a descriptor.
  316. *
  317. * @see javassist.bytecode.Descriptor
  318. * @see #getGenericSignature()
  319. */
  320. @Override
  321. public String getSignature() {
  322. return fieldInfo.getDescriptor();
  323. }
  324. /**
  325. * Returns the generic signature of the field.
  326. * It represents a type including type variables.
  327. *
  328. * @see SignatureAttribute#toFieldSignature(String)
  329. * @since 3.17
  330. */
  331. @Override
  332. public String getGenericSignature() {
  333. SignatureAttribute sa
  334. = (SignatureAttribute)fieldInfo.getAttribute(SignatureAttribute.tag);
  335. return sa == null ? null : sa.getSignature();
  336. }
  337. /**
  338. * Set the generic signature of the field.
  339. * It represents a type including type variables.
  340. * See {@link javassist.CtClass#setGenericSignature(String)}
  341. * for a code sample.
  342. *
  343. * @param sig a new generic signature.
  344. * @see javassist.bytecode.SignatureAttribute.ObjectType#encode()
  345. * @since 3.17
  346. */
  347. @Override
  348. public void setGenericSignature(String sig) {
  349. declaringClass.checkModify();
  350. fieldInfo.addAttribute(new SignatureAttribute(fieldInfo.getConstPool(), sig));
  351. }
  352. /**
  353. * Returns the type of the field.
  354. */
  355. public CtClass getType() throws NotFoundException {
  356. return Descriptor.toCtClass(fieldInfo.getDescriptor(),
  357. declaringClass.getClassPool());
  358. }
  359. /**
  360. * Sets the type of the field.
  361. *
  362. * <p>This method does not automatically update method bodies that access
  363. * this field. They have to be explicitly updated. For example,
  364. * if some method contains an expression {@code t.value} and the type
  365. * of the variable {@code t} is changed by {@link #setType(CtClass)}
  366. * from {@code int} to {@code double}, then {@code t.value} has to be modified
  367. * as well since the bytecode of {@code t.value} contains the type information.
  368. * </p>
  369. *
  370. * @see CodeConverter
  371. * @see javassist.expr.ExprEditor
  372. */
  373. public void setType(CtClass clazz) {
  374. declaringClass.checkModify();
  375. fieldInfo.setDescriptor(Descriptor.of(clazz));
  376. }
  377. /**
  378. * Returns the value of this field if it is a constant field.
  379. * This method works only if the field type is a primitive type
  380. * or <code>String</code> type. Otherwise, it returns <code>null</code>.
  381. * A constant field is <code>static</code> and <code>final</code>.
  382. *
  383. * @return a <code>Integer</code>, <code>Long</code>, <code>Float</code>,
  384. * <code>Double</code>, <code>Boolean</code>,
  385. * or <code>String</code> object
  386. * representing the constant value.
  387. * <code>null</code> if it is not a constant field
  388. * or if the field type is not a primitive type
  389. * or <code>String</code>.
  390. */
  391. public Object getConstantValue() {
  392. // When this method is modified,
  393. // see also getConstantFieldValue() in TypeChecker.
  394. int index = fieldInfo.getConstantValue();
  395. if (index == 0)
  396. return null;
  397. ConstPool cp = fieldInfo.getConstPool();
  398. switch (cp.getTag(index)) {
  399. case ConstPool.CONST_Long :
  400. return Long.valueOf(cp.getLongInfo(index));
  401. case ConstPool.CONST_Float :
  402. return Float.valueOf(cp.getFloatInfo(index));
  403. case ConstPool.CONST_Double :
  404. return Double.valueOf(cp.getDoubleInfo(index));
  405. case ConstPool.CONST_Integer :
  406. int value = cp.getIntegerInfo(index);
  407. // "Z" means boolean type.
  408. if ("Z".equals(fieldInfo.getDescriptor()))
  409. return Boolean.valueOf(value != 0);
  410. return Integer.valueOf(value);
  411. case ConstPool.CONST_String :
  412. return cp.getStringInfo(index);
  413. default :
  414. throw new RuntimeException("bad tag: " + cp.getTag(index)
  415. + " at " + index);
  416. }
  417. }
  418. /**
  419. * Obtains an attribute with the given name.
  420. * If that attribute is not found in the class file, this
  421. * method returns null.
  422. *
  423. * <p>Note that an attribute is a data block specified by
  424. * the class file format.
  425. * See {@link javassist.bytecode.AttributeInfo}.
  426. *
  427. * @param name attribute name
  428. */
  429. @Override
  430. public byte[] getAttribute(String name) {
  431. AttributeInfo ai = fieldInfo.getAttribute(name);
  432. if (ai == null)
  433. return null;
  434. return ai.get();
  435. }
  436. /**
  437. * Adds an attribute. The attribute is saved in the class file.
  438. *
  439. * <p>Note that an attribute is a data block specified by
  440. * the class file format.
  441. * See {@link javassist.bytecode.AttributeInfo}.
  442. *
  443. * @param name attribute name
  444. * @param data attribute value
  445. */
  446. @Override
  447. public void setAttribute(String name, byte[] data) {
  448. declaringClass.checkModify();
  449. fieldInfo.addAttribute(new AttributeInfo(fieldInfo.getConstPool(),
  450. name, data));
  451. }
  452. // inner classes
  453. /**
  454. * Instances of this class specify how to initialize a field.
  455. * <code>Initializer</code> is passed to
  456. * <code>CtClass.addField()</code> with a <code>CtField</code>.
  457. *
  458. * <p>This class cannot be instantiated with the <code>new</code> operator.
  459. * Factory methods such as <code>byParameter()</code> and
  460. * <code>byNew</code>
  461. * must be used for the instantiation. They create a new instance with
  462. * the given parameters and return it.
  463. *
  464. * @see CtClass#addField(CtField,CtField.Initializer)
  465. */
  466. public static abstract class Initializer {
  467. /**
  468. * Makes an initializer that assigns a constant integer value.
  469. * The field must be integer, short, char, or byte type.
  470. */
  471. public static Initializer constant(int i) {
  472. return new IntInitializer(i);
  473. }
  474. /**
  475. * Makes an initializer that assigns a constant boolean value.
  476. * The field must be boolean type.
  477. */
  478. public static Initializer constant(boolean b) {
  479. return new IntInitializer(b ? 1 : 0);
  480. }
  481. /**
  482. * Makes an initializer that assigns a constant long value.
  483. * The field must be long type.
  484. */
  485. public static Initializer constant(long l) {
  486. return new LongInitializer(l);
  487. }
  488. /**
  489. * Makes an initializer that assigns a constant float value.
  490. * The field must be float type.
  491. */
  492. public static Initializer constant(float l) {
  493. return new FloatInitializer(l);
  494. }
  495. /**
  496. * Makes an initializer that assigns a constant double value.
  497. * The field must be double type.
  498. */
  499. public static Initializer constant(double d) {
  500. return new DoubleInitializer(d);
  501. }
  502. /**
  503. * Makes an initializer that assigns a constant string value.
  504. * The field must be <code>java.lang.String</code> type.
  505. */
  506. public static Initializer constant(String s) {
  507. return new StringInitializer(s);
  508. }
  509. /**
  510. * Makes an initializer using a constructor parameter.
  511. *
  512. * <p>The initial value is the
  513. * N-th parameter given to the constructor of the object including
  514. * the field. If the constructor takes less than N parameters,
  515. * the field is not initialized.
  516. * If the field is static, it is never initialized.
  517. *
  518. * @param nth the n-th (&gt;= 0) parameter is used as
  519. * the initial value.
  520. * If nth is 0, then the first parameter is
  521. * used.
  522. */
  523. public static Initializer byParameter(int nth) {
  524. ParamInitializer i = new ParamInitializer();
  525. i.nthParam = nth;
  526. return i;
  527. }
  528. /**
  529. * Makes an initializer creating a new object.
  530. *
  531. * <p>This initializer creates a new object and uses it as the initial
  532. * value of the field. The constructor of the created object receives
  533. * the parameter:
  534. *
  535. * <p><code>Object obj</code> - the object including the field.
  536. *
  537. * <p>If the initialized field is static, then the constructor does
  538. * not receive any parameters.
  539. *
  540. * @param objectType the class instantiated for the initial value.
  541. */
  542. public static Initializer byNew(CtClass objectType) {
  543. NewInitializer i = new NewInitializer();
  544. i.objectType = objectType;
  545. i.stringParams = null;
  546. i.withConstructorParams = false;
  547. return i;
  548. }
  549. /**
  550. * Makes an initializer creating a new object.
  551. *
  552. * <p>This initializer creates a new object and uses it as the initial
  553. * value of the field. The constructor of the created object receives
  554. * the parameters:
  555. *
  556. * <p><code>Object obj</code> - the object including the field.<br>
  557. * <code>String[] strs</code> - the character strings specified
  558. * by <code>stringParams</code><br>
  559. *
  560. * <p>If the initialized field is static, then the constructor
  561. * receives only <code>strs</code>.
  562. *
  563. * @param objectType the class instantiated for the initial value.
  564. * @param stringParams the array of strings passed to the
  565. * constructor.
  566. */
  567. public static Initializer byNew(CtClass objectType,
  568. String[] stringParams) {
  569. NewInitializer i = new NewInitializer();
  570. i.objectType = objectType;
  571. i.stringParams = stringParams;
  572. i.withConstructorParams = false;
  573. return i;
  574. }
  575. /**
  576. * Makes an initializer creating a new object.
  577. *
  578. * <p>This initializer creates a new object and uses it as the initial
  579. * value of the field. The constructor of the created object receives
  580. * the parameters:
  581. *
  582. * <p><code>Object obj</code> - the object including the field.<br>
  583. * <code>Object[] args</code> - the parameters passed to the
  584. * constructor of the object including the
  585. * filed.
  586. *
  587. * <p>If the initialized field is static, then the constructor does
  588. * not receive any parameters.
  589. *
  590. * @param objectType the class instantiated for the initial value.
  591. *
  592. * @see javassist.CtField.Initializer#byNewArray(CtClass,int)
  593. * @see javassist.CtField.Initializer#byNewArray(CtClass,int[])
  594. */
  595. public static Initializer byNewWithParams(CtClass objectType) {
  596. NewInitializer i = new NewInitializer();
  597. i.objectType = objectType;
  598. i.stringParams = null;
  599. i.withConstructorParams = true;
  600. return i;
  601. }
  602. /**
  603. * Makes an initializer creating a new object.
  604. *
  605. * <p>This initializer creates a new object and uses it as the initial
  606. * value of the field. The constructor of the created object receives
  607. * the parameters:
  608. *
  609. * <p><code>Object obj</code> - the object including the field.<br>
  610. * <code>String[] strs</code> - the character strings specified
  611. * by <code>stringParams</code><br>
  612. * <code>Object[] args</code> - the parameters passed to the
  613. * constructor of the object including the
  614. * filed.
  615. *
  616. * <p>If the initialized field is static, then the constructor receives
  617. * only <code>strs</code>.
  618. *
  619. * @param objectType the class instantiated for the initial value.
  620. * @param stringParams the array of strings passed to the
  621. * constructor.
  622. */
  623. public static Initializer byNewWithParams(CtClass objectType,
  624. String[] stringParams) {
  625. NewInitializer i = new NewInitializer();
  626. i.objectType = objectType;
  627. i.stringParams = stringParams;
  628. i.withConstructorParams = true;
  629. return i;
  630. }
  631. /**
  632. * Makes an initializer calling a static method.
  633. *
  634. * <p>This initializer calls a static method and uses the returned
  635. * value as the initial value of the field.
  636. * The called method receives the parameters:
  637. *
  638. * <p><code>Object obj</code> - the object including the field.
  639. *
  640. * <p>If the initialized field is static, then the method does
  641. * not receive any parameters.
  642. *
  643. * <p>The type of the returned value must be the same as the field
  644. * type.
  645. *
  646. * @param methodClass the class that the static method is
  647. * declared in.
  648. * @param methodName the name of the satic method.
  649. */
  650. public static Initializer byCall(CtClass methodClass,
  651. String methodName) {
  652. MethodInitializer i = new MethodInitializer();
  653. i.objectType = methodClass;
  654. i.methodName = methodName;
  655. i.stringParams = null;
  656. i.withConstructorParams = false;
  657. return i;
  658. }
  659. /**
  660. * Makes an initializer calling a static method.
  661. *
  662. * <p>This initializer calls a static method and uses the returned
  663. * value as the initial value of the field. The called method
  664. * receives the parameters:
  665. *
  666. * <p><code>Object obj</code> - the object including the field.<br>
  667. * <code>String[] strs</code> - the character strings specified
  668. * by <code>stringParams</code><br>
  669. *
  670. * <p>If the initialized field is static, then the method
  671. * receive only <code>strs</code>.
  672. *
  673. * <p>The type of the returned value must be the same as the field
  674. * type.
  675. *
  676. * @param methodClass the class that the static method is
  677. * declared in.
  678. * @param methodName the name of the satic method.
  679. * @param stringParams the array of strings passed to the
  680. * static method.
  681. */
  682. public static Initializer byCall(CtClass methodClass,
  683. String methodName,
  684. String[] stringParams) {
  685. MethodInitializer i = new MethodInitializer();
  686. i.objectType = methodClass;
  687. i.methodName = methodName;
  688. i.stringParams = stringParams;
  689. i.withConstructorParams = false;
  690. return i;
  691. }
  692. /**
  693. * Makes an initializer calling a static method.
  694. *
  695. * <p>This initializer calls a static method and uses the returned
  696. * value as the initial value of the field. The called method
  697. * receives the parameters:
  698. *
  699. * <p><code>Object obj</code> - the object including the field.<br>
  700. * <code>Object[] args</code> - the parameters passed to the
  701. * constructor of the object including the
  702. * filed.
  703. *
  704. * <p>If the initialized field is static, then the method does
  705. * not receive any parameters.
  706. *
  707. * <p>The type of the returned value must be the same as the field
  708. * type.
  709. *
  710. * @param methodClass the class that the static method is
  711. * declared in.
  712. * @param methodName the name of the satic method.
  713. */
  714. public static Initializer byCallWithParams(CtClass methodClass,
  715. String methodName) {
  716. MethodInitializer i = new MethodInitializer();
  717. i.objectType = methodClass;
  718. i.methodName = methodName;
  719. i.stringParams = null;
  720. i.withConstructorParams = true;
  721. return i;
  722. }
  723. /**
  724. * Makes an initializer calling a static method.
  725. *
  726. * <p>This initializer calls a static method and uses the returned
  727. * value as the initial value of the field. The called method
  728. * receives the parameters:
  729. *
  730. * <p><code>Object obj</code> - the object including the field.<br>
  731. * <code>String[] strs</code> - the character strings specified
  732. * by <code>stringParams</code><br>
  733. * <code>Object[] args</code> - the parameters passed to the
  734. * constructor of the object including the
  735. * filed.
  736. *
  737. * <p>If the initialized field is static, then the method
  738. * receive only <code>strs</code>.
  739. *
  740. * <p>The type of the returned value must be the same as the field
  741. * type.
  742. *
  743. * @param methodClass the class that the static method is
  744. * declared in.
  745. * @param methodName the name of the satic method.
  746. * @param stringParams the array of strings passed to the
  747. * static method.
  748. */
  749. public static Initializer byCallWithParams(CtClass methodClass,
  750. String methodName, String[] stringParams) {
  751. MethodInitializer i = new MethodInitializer();
  752. i.objectType = methodClass;
  753. i.methodName = methodName;
  754. i.stringParams = stringParams;
  755. i.withConstructorParams = true;
  756. return i;
  757. }
  758. /**
  759. * Makes an initializer creating a new array.
  760. *
  761. * @param type the type of the array.
  762. * @param size the size of the array.
  763. * @throws NotFoundException if the type of the array components
  764. * is not found.
  765. */
  766. public static Initializer byNewArray(CtClass type, int size)
  767. throws NotFoundException
  768. {
  769. return new ArrayInitializer(type.getComponentType(), size);
  770. }
  771. /**
  772. * Makes an initializer creating a new multi-dimensional array.
  773. *
  774. * @param type the type of the array.
  775. * @param sizes an <code>int</code> array of the size in every
  776. * dimension.
  777. * The first element is the size in the first
  778. * dimension. The second is in the second, etc.
  779. */
  780. public static Initializer byNewArray(CtClass type, int[] sizes) {
  781. return new MultiArrayInitializer(type, sizes);
  782. }
  783. /**
  784. * Makes an initializer.
  785. *
  786. * @param source initializer expression.
  787. */
  788. public static Initializer byExpr(String source) {
  789. return new CodeInitializer(source);
  790. }
  791. static Initializer byExpr(ASTree source) {
  792. return new PtreeInitializer(source);
  793. }
  794. // Check whether this initializer is valid for the field type.
  795. // If it is invaild, this method throws an exception.
  796. void check(String desc) throws CannotCompileException {}
  797. // produce codes for initialization
  798. abstract int compile(CtClass type, String name, Bytecode code,
  799. CtClass[] parameters, Javac drv)
  800. throws CannotCompileException;
  801. // produce codes for initialization
  802. abstract int compileIfStatic(CtClass type, String name,
  803. Bytecode code, Javac drv) throws CannotCompileException;
  804. // returns the index of CONSTANT_Integer_info etc
  805. // if the value is constant. Otherwise, 0.
  806. int getConstantValue(ConstPool cp, CtClass type) { return 0; }
  807. }
  808. static abstract class CodeInitializer0 extends Initializer {
  809. abstract void compileExpr(Javac drv) throws CompileError;
  810. @Override
  811. int compile(CtClass type, String name, Bytecode code,
  812. CtClass[] parameters, Javac drv)
  813. throws CannotCompileException
  814. {
  815. try {
  816. code.addAload(0);
  817. compileExpr(drv);
  818. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  819. return code.getMaxStack();
  820. }
  821. catch (CompileError e) {
  822. throw new CannotCompileException(e);
  823. }
  824. }
  825. @Override
  826. int compileIfStatic(CtClass type, String name, Bytecode code,
  827. Javac drv) throws CannotCompileException
  828. {
  829. try {
  830. compileExpr(drv);
  831. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  832. return code.getMaxStack();
  833. }
  834. catch (CompileError e) {
  835. throw new CannotCompileException(e);
  836. }
  837. }
  838. int getConstantValue2(ConstPool cp, CtClass type, ASTree tree) {
  839. if (type.isPrimitive()) {
  840. if (tree instanceof IntConst) {
  841. long value = ((IntConst)tree).get();
  842. if (type == CtClass.doubleType)
  843. return cp.addDoubleInfo(value);
  844. else if (type == CtClass.floatType)
  845. return cp.addFloatInfo(value);
  846. else if (type == CtClass.longType)
  847. return cp.addLongInfo(value);
  848. else if (type != CtClass.voidType)
  849. return cp.addIntegerInfo((int)value);
  850. }
  851. else if (tree instanceof DoubleConst) {
  852. double value = ((DoubleConst)tree).get();
  853. if (type == CtClass.floatType)
  854. return cp.addFloatInfo((float)value);
  855. else if (type == CtClass.doubleType)
  856. return cp.addDoubleInfo(value);
  857. }
  858. }
  859. else if (tree instanceof StringL
  860. && type.getName().equals(javaLangString))
  861. return cp.addStringInfo(((StringL)tree).get());
  862. return 0;
  863. }
  864. }
  865. static class CodeInitializer extends CodeInitializer0 {
  866. private String expression;
  867. CodeInitializer(String expr) { expression = expr; }
  868. @Override
  869. void compileExpr(Javac drv) throws CompileError {
  870. drv.compileExpr(expression);
  871. }
  872. @Override
  873. int getConstantValue(ConstPool cp, CtClass type) {
  874. try {
  875. ASTree t = Javac.parseExpr(expression, new SymbolTable());
  876. return getConstantValue2(cp, type, t);
  877. }
  878. catch (CompileError e) {
  879. return 0;
  880. }
  881. }
  882. }
  883. static class PtreeInitializer extends CodeInitializer0 {
  884. private ASTree expression;
  885. PtreeInitializer(ASTree expr) { expression = expr; }
  886. @Override
  887. void compileExpr(Javac drv) throws CompileError {
  888. drv.compileExpr(expression);
  889. }
  890. @Override
  891. int getConstantValue(ConstPool cp, CtClass type) {
  892. return getConstantValue2(cp, type, expression);
  893. }
  894. }
  895. /**
  896. * A field initialized with a parameter passed to the constructor
  897. * of the class containing that field.
  898. */
  899. static class ParamInitializer extends Initializer {
  900. int nthParam;
  901. ParamInitializer() {}
  902. @Override
  903. int compile(CtClass type, String name, Bytecode code,
  904. CtClass[] parameters, Javac drv)
  905. throws CannotCompileException
  906. {
  907. if (parameters != null && nthParam < parameters.length) {
  908. code.addAload(0);
  909. int nth = nthParamToLocal(nthParam, parameters, false);
  910. int s = code.addLoad(nth, type) + 1;
  911. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  912. return s; // stack size
  913. }
  914. return 0; // do not initialize
  915. }
  916. /**
  917. * Computes the index of the local variable that the n-th parameter
  918. * is assigned to.
  919. *
  920. * @param nth n-th parameter
  921. * @param params list of parameter types
  922. * @param isStatic true if the method is static.
  923. */
  924. static int nthParamToLocal(int nth, CtClass[] params,
  925. boolean isStatic) {
  926. CtClass longType = CtClass.longType;
  927. CtClass doubleType = CtClass.doubleType;
  928. int k;
  929. if (isStatic)
  930. k = 0;
  931. else
  932. k = 1; // 0 is THIS.
  933. for (int i = 0; i < nth; ++i) {
  934. CtClass type = params[i];
  935. if (type == longType || type == doubleType)
  936. k += 2;
  937. else
  938. ++k;
  939. }
  940. return k;
  941. }
  942. @Override
  943. int compileIfStatic(CtClass type, String name, Bytecode code,
  944. Javac drv) throws CannotCompileException
  945. {
  946. return 0;
  947. }
  948. }
  949. /**
  950. * A field initialized with an object created by the new operator.
  951. */
  952. static class NewInitializer extends Initializer {
  953. CtClass objectType;
  954. String[] stringParams;
  955. boolean withConstructorParams;
  956. NewInitializer() {}
  957. /**
  958. * Produces codes in which a new object is created and assigned to
  959. * the field as the initial value.
  960. */
  961. @Override
  962. int compile(CtClass type, String name, Bytecode code,
  963. CtClass[] parameters, Javac drv)
  964. throws CannotCompileException
  965. {
  966. int stacksize;
  967. code.addAload(0);
  968. code.addNew(objectType);
  969. code.add(Bytecode.DUP);
  970. code.addAload(0);
  971. if (stringParams == null)
  972. stacksize = 4;
  973. else
  974. stacksize = compileStringParameter(code) + 4;
  975. if (withConstructorParams)
  976. stacksize += CtNewWrappedMethod.compileParameterList(code,
  977. parameters, 1);
  978. code.addInvokespecial(objectType, "<init>", getDescriptor());
  979. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  980. return stacksize;
  981. }
  982. private String getDescriptor() {
  983. final String desc3
  984. = "(Ljava/lang/Object;[Ljava/lang/String;[Ljava/lang/Object;)V";
  985. if (stringParams == null)
  986. if (withConstructorParams)
  987. return "(Ljava/lang/Object;[Ljava/lang/Object;)V";
  988. else
  989. return "(Ljava/lang/Object;)V";
  990. if (withConstructorParams)
  991. return desc3;
  992. return "(Ljava/lang/Object;[Ljava/lang/String;)V";
  993. }
  994. /**
  995. * Produces codes for a static field.
  996. */
  997. @Override
  998. int compileIfStatic(CtClass type, String name, Bytecode code,
  999. Javac drv) throws CannotCompileException
  1000. {
  1001. String desc;
  1002. code.addNew(objectType);
  1003. code.add(Bytecode.DUP);
  1004. int stacksize = 2;
  1005. if (stringParams == null)
  1006. desc = "()V";
  1007. else {
  1008. desc = "([Ljava/lang/String;)V";
  1009. stacksize += compileStringParameter(code);
  1010. }
  1011. code.addInvokespecial(objectType, "<init>", desc);
  1012. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1013. return stacksize;
  1014. }
  1015. protected final int compileStringParameter(Bytecode code)
  1016. throws CannotCompileException
  1017. {
  1018. int nparam = stringParams.length;
  1019. code.addIconst(nparam);
  1020. code.addAnewarray(javaLangString);
  1021. for (int j = 0; j < nparam; ++j) {
  1022. code.add(Bytecode.DUP); // dup
  1023. code.addIconst(j); // iconst_<j>
  1024. code.addLdc(stringParams[j]); // ldc ...
  1025. code.add(Bytecode.AASTORE); // aastore
  1026. }
  1027. return 4;
  1028. }
  1029. }
  1030. /**
  1031. * A field initialized with the result of a static method call.
  1032. */
  1033. static class MethodInitializer extends NewInitializer {
  1034. String methodName;
  1035. // the method class is specified by objectType.
  1036. MethodInitializer() {}
  1037. /**
  1038. * Produces codes in which a new object is created and assigned to
  1039. * the field as the initial value.
  1040. */
  1041. @Override
  1042. int compile(CtClass type, String name, Bytecode code,
  1043. CtClass[] parameters, Javac drv)
  1044. throws CannotCompileException
  1045. {
  1046. int stacksize;
  1047. code.addAload(0);
  1048. code.addAload(0);
  1049. if (stringParams == null)
  1050. stacksize = 2;
  1051. else
  1052. stacksize = compileStringParameter(code) + 2;
  1053. if (withConstructorParams)
  1054. stacksize += CtNewWrappedMethod.compileParameterList(code,
  1055. parameters, 1);
  1056. String typeDesc = Descriptor.of(type);
  1057. String mDesc = getDescriptor() + typeDesc;
  1058. code.addInvokestatic(objectType, methodName, mDesc);
  1059. code.addPutfield(Bytecode.THIS, name, typeDesc);
  1060. return stacksize;
  1061. }
  1062. private String getDescriptor() {
  1063. final String desc3
  1064. = "(Ljava/lang/Object;[Ljava/lang/String;[Ljava/lang/Object;)";
  1065. if (stringParams == null)
  1066. if (withConstructorParams)
  1067. return "(Ljava/lang/Object;[Ljava/lang/Object;)";
  1068. else
  1069. return "(Ljava/lang/Object;)";
  1070. if (withConstructorParams)
  1071. return desc3;
  1072. return "(Ljava/lang/Object;[Ljava/lang/String;)";
  1073. }
  1074. /**
  1075. * Produces codes for a static field.
  1076. */
  1077. @Override
  1078. int compileIfStatic(CtClass type, String name, Bytecode code,
  1079. Javac drv) throws CannotCompileException
  1080. {
  1081. String desc;
  1082. int stacksize = 1;
  1083. if (stringParams == null)
  1084. desc = "()";
  1085. else {
  1086. desc = "([Ljava/lang/String;)";
  1087. stacksize += compileStringParameter(code);
  1088. }
  1089. String typeDesc = Descriptor.of(type);
  1090. code.addInvokestatic(objectType, methodName, desc + typeDesc);
  1091. code.addPutstatic(Bytecode.THIS, name, typeDesc);
  1092. return stacksize;
  1093. }
  1094. }
  1095. static class IntInitializer extends Initializer {
  1096. int value;
  1097. IntInitializer(int v) { value = v; }
  1098. @Override
  1099. void check(String desc) throws CannotCompileException {
  1100. char c = desc.charAt(0);
  1101. if (c != 'I' && c != 'S' && c != 'B' && c != 'C' && c != 'Z')
  1102. throw new CannotCompileException("type mismatch");
  1103. }
  1104. @Override
  1105. int compile(CtClass type, String name, Bytecode code,
  1106. CtClass[] parameters, Javac drv)
  1107. throws CannotCompileException
  1108. {
  1109. code.addAload(0);
  1110. code.addIconst(value);
  1111. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1112. return 2; // stack size
  1113. }
  1114. @Override
  1115. int compileIfStatic(CtClass type, String name, Bytecode code,
  1116. Javac drv) throws CannotCompileException
  1117. {
  1118. code.addIconst(value);
  1119. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1120. return 1; // stack size
  1121. }
  1122. @Override
  1123. int getConstantValue(ConstPool cp, CtClass type) {
  1124. return cp.addIntegerInfo(value);
  1125. }
  1126. }
  1127. static class LongInitializer extends Initializer {
  1128. long value;
  1129. LongInitializer(long v) { value = v; }
  1130. @Override
  1131. void check(String desc) throws CannotCompileException {
  1132. if (!desc.equals("J"))
  1133. throw new CannotCompileException("type mismatch");
  1134. }
  1135. @Override
  1136. int compile(CtClass type, String name, Bytecode code,
  1137. CtClass[] parameters, Javac drv)
  1138. throws CannotCompileException
  1139. {
  1140. code.addAload(0);
  1141. code.addLdc2w(value);
  1142. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1143. return 3; // stack size
  1144. }
  1145. @Override
  1146. int compileIfStatic(CtClass type, String name, Bytecode code,
  1147. Javac drv) throws CannotCompileException
  1148. {
  1149. code.addLdc2w(value);
  1150. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1151. return 2; // stack size
  1152. }
  1153. @Override
  1154. int getConstantValue(ConstPool cp, CtClass type) {
  1155. if (type == CtClass.longType)
  1156. return cp.addLongInfo(value);
  1157. return 0;
  1158. }
  1159. }
  1160. static class FloatInitializer extends Initializer {
  1161. float value;
  1162. FloatInitializer(float v) { value = v; }
  1163. @Override
  1164. void check(String desc) throws CannotCompileException {
  1165. if (!desc.equals("F"))
  1166. throw new CannotCompileException("type mismatch");
  1167. }
  1168. @Override
  1169. int compile(CtClass type, String name, Bytecode code,
  1170. CtClass[] parameters, Javac drv)
  1171. throws CannotCompileException
  1172. {
  1173. code.addAload(0);
  1174. code.addFconst(value);
  1175. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1176. return 3; // stack size
  1177. }
  1178. @Override
  1179. int compileIfStatic(CtClass type, String name, Bytecode code,
  1180. Javac drv) throws CannotCompileException
  1181. {
  1182. code.addFconst(value);
  1183. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1184. return 2; // stack size
  1185. }
  1186. @Override
  1187. int getConstantValue(ConstPool cp, CtClass type) {
  1188. if (type == CtClass.floatType)
  1189. return cp.addFloatInfo(value);
  1190. return 0;
  1191. }
  1192. }
  1193. static class DoubleInitializer extends Initializer {
  1194. double value;
  1195. DoubleInitializer(double v) { value = v; }
  1196. @Override
  1197. void check(String desc) throws CannotCompileException {
  1198. if (!desc.equals("D"))
  1199. throw new CannotCompileException("type mismatch");
  1200. }
  1201. @Override
  1202. int compile(CtClass type, String name, Bytecode code,
  1203. CtClass[] parameters, Javac drv)
  1204. throws CannotCompileException
  1205. {
  1206. code.addAload(0);
  1207. code.addLdc2w(value);
  1208. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1209. return 3; // stack size
  1210. }
  1211. @Override
  1212. int compileIfStatic(CtClass type, String name, Bytecode code,
  1213. Javac drv) throws CannotCompileException
  1214. {
  1215. code.addLdc2w(value);
  1216. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1217. return 2; // stack size
  1218. }
  1219. @Override
  1220. int getConstantValue(ConstPool cp, CtClass type) {
  1221. if (type == CtClass.doubleType)
  1222. return cp.addDoubleInfo(value);
  1223. return 0;
  1224. }
  1225. }
  1226. static class StringInitializer extends Initializer {
  1227. String value;
  1228. StringInitializer(String v) { value = v; }
  1229. @Override
  1230. int compile(CtClass type, String name, Bytecode code,
  1231. CtClass[] parameters, Javac drv)
  1232. throws CannotCompileException
  1233. {
  1234. code.addAload(0);
  1235. code.addLdc(value);
  1236. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1237. return 2; // stack size
  1238. }
  1239. @Override
  1240. int compileIfStatic(CtClass type, String name, Bytecode code,
  1241. Javac drv) throws CannotCompileException
  1242. {
  1243. code.addLdc(value);
  1244. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1245. return 1; // stack size
  1246. }
  1247. @Override
  1248. int getConstantValue(ConstPool cp, CtClass type) {
  1249. if (type.getName().equals(javaLangString))
  1250. return cp.addStringInfo(value);
  1251. return 0;
  1252. }
  1253. }
  1254. static class ArrayInitializer extends Initializer {
  1255. CtClass type;
  1256. int size;
  1257. ArrayInitializer(CtClass t, int s) { type = t; size = s; }
  1258. private void addNewarray(Bytecode code) {
  1259. if (type.isPrimitive())
  1260. code.addNewarray(((CtPrimitiveType)type).getArrayType(),
  1261. size);
  1262. else
  1263. code.addAnewarray(type, size);
  1264. }
  1265. @Override
  1266. int compile(CtClass type, String name, Bytecode code,
  1267. CtClass[] parameters, Javac drv)
  1268. throws CannotCompileException
  1269. {
  1270. code.addAload(0);
  1271. addNewarray(code);
  1272. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1273. return 2; // stack size
  1274. }
  1275. @Override
  1276. int compileIfStatic(CtClass type, String name, Bytecode code,
  1277. Javac drv) throws CannotCompileException
  1278. {
  1279. addNewarray(code);
  1280. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1281. return 1; // stack size
  1282. }
  1283. }
  1284. static class MultiArrayInitializer extends Initializer {
  1285. CtClass type;
  1286. int[] dim;
  1287. MultiArrayInitializer(CtClass t, int[] d) { type = t; dim = d; }
  1288. @Override
  1289. void check(String desc) throws CannotCompileException {
  1290. if (desc.charAt(0) != '[')
  1291. throw new CannotCompileException("type mismatch");
  1292. }
  1293. @Override
  1294. int compile(CtClass type, String name, Bytecode code,
  1295. CtClass[] parameters, Javac drv)
  1296. throws CannotCompileException
  1297. {
  1298. code.addAload(0);
  1299. int s = code.addMultiNewarray(type, dim);
  1300. code.addPutfield(Bytecode.THIS, name, Descriptor.of(type));
  1301. return s + 1; // stack size
  1302. }
  1303. @Override
  1304. int compileIfStatic(CtClass type, String name, Bytecode code,
  1305. Javac drv) throws CannotCompileException
  1306. {
  1307. int s = code.addMultiNewarray(type, dim);
  1308. code.addPutstatic(Bytecode.THIS, name, Descriptor.of(type));
  1309. return s; // stack size
  1310. }
  1311. }
  1312. }