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 48KB

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