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.

CtField.java 44KB

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