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.

CtClassType.java 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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 java.io.BufferedInputStream;
  17. import java.io.DataInputStream;
  18. import java.io.DataOutputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.net.URL;
  22. import java.util.ArrayList;
  23. import java.util.Enumeration;
  24. import java.util.HashMap;
  25. import java.util.Hashtable;
  26. import java.util.List;
  27. import java.util.Set;
  28. import javassist.bytecode.AccessFlag;
  29. import javassist.bytecode.AttributeInfo;
  30. import javassist.bytecode.AnnotationsAttribute;
  31. import javassist.bytecode.BadBytecode;
  32. import javassist.bytecode.Bytecode;
  33. import javassist.bytecode.ClassFile;
  34. import javassist.bytecode.CodeAttribute;
  35. import javassist.bytecode.ConstantAttribute;
  36. import javassist.bytecode.CodeIterator;
  37. import javassist.bytecode.ConstPool;
  38. import javassist.bytecode.Descriptor;
  39. import javassist.bytecode.EnclosingMethodAttribute;
  40. import javassist.bytecode.FieldInfo;
  41. import javassist.bytecode.InnerClassesAttribute;
  42. import javassist.bytecode.MethodInfo;
  43. import javassist.bytecode.ParameterAnnotationsAttribute;
  44. import javassist.bytecode.annotation.Annotation;
  45. import javassist.compiler.AccessorMaker;
  46. import javassist.compiler.CompileError;
  47. import javassist.compiler.Javac;
  48. import javassist.expr.ExprEditor;
  49. /**
  50. * Class types.
  51. */
  52. class CtClassType extends CtClass {
  53. ClassPool classPool;
  54. boolean wasChanged;
  55. private boolean wasFrozen;
  56. boolean wasPruned;
  57. boolean memberRemoved;
  58. ClassFile classfile;
  59. private CtMember fieldsCache;
  60. private CtMember methodsCache;
  61. private CtMember constructorsCache;
  62. private CtConstructor classInitializerCache;
  63. private AccessorMaker accessors;
  64. private FieldInitLink fieldInitializers;
  65. private Hashtable hiddenMethods; // must be synchronous
  66. private int uniqueNumberSeed;
  67. private boolean doPruning = ClassPool.doPruning;
  68. int getCounter;
  69. private static int readCounter = 0;
  70. private static final int READ_THRESHOLD = 100; // see getClassFile2()
  71. CtClassType(String name, ClassPool cp) {
  72. super(name);
  73. classPool = cp;
  74. wasChanged = wasFrozen = wasPruned = memberRemoved = false;
  75. classfile = null;
  76. accessors = null;
  77. fieldInitializers = null;
  78. hiddenMethods = null;
  79. uniqueNumberSeed = 0;
  80. eraseCache();
  81. getCounter = 0;
  82. }
  83. CtClassType(InputStream ins, ClassPool cp) throws IOException {
  84. this((String)null, cp);
  85. classfile = new ClassFile(new DataInputStream(ins));
  86. qualifiedName = classfile.getName();
  87. }
  88. protected void extendToString(StringBuffer buffer) {
  89. if (wasChanged)
  90. buffer.append("changed ");
  91. if (wasFrozen)
  92. buffer.append("frozen ");
  93. if (wasPruned)
  94. buffer.append("pruned ");
  95. buffer.append(Modifier.toString(getModifiers()));
  96. buffer.append(" class ");
  97. buffer.append(getName());
  98. try {
  99. CtClass ext = getSuperclass();
  100. if (ext != null) {
  101. String name = ext.getName();
  102. if (!name.equals("java.lang.Object"))
  103. buffer.append(" extends " + ext.getName());
  104. }
  105. }
  106. catch (NotFoundException e) {
  107. buffer.append(" extends ??");
  108. }
  109. try {
  110. CtClass[] intf = getInterfaces();
  111. if (intf.length > 0)
  112. buffer.append(" implements ");
  113. for (int i = 0; i < intf.length; ++i) {
  114. buffer.append(intf[i].getName());
  115. buffer.append(", ");
  116. }
  117. }
  118. catch (NotFoundException e) {
  119. buffer.append(" extends ??");
  120. }
  121. CtMember field = getFieldsCache();
  122. buffer.append(" fields=");
  123. while (field != null) {
  124. buffer.append(field);
  125. buffer.append(", ");
  126. field = field.next;
  127. }
  128. CtMember c = getConstructorsCache();
  129. buffer.append(" constructors=");
  130. while (c != null) {
  131. buffer.append(c);
  132. buffer.append(", ");
  133. c = c.next;
  134. }
  135. CtMember m = getMethodsCache();
  136. buffer.append(" methods=");
  137. while (m != null) {
  138. buffer.append(m);
  139. buffer.append(", ");
  140. m = m.next;
  141. }
  142. }
  143. protected void eraseCache() {
  144. fieldsCache = null;
  145. constructorsCache = null;
  146. classInitializerCache = null;
  147. methodsCache = null;
  148. }
  149. public AccessorMaker getAccessorMaker() {
  150. if (accessors == null)
  151. accessors = new AccessorMaker(this);
  152. return accessors;
  153. }
  154. public ClassFile getClassFile2() {
  155. if (classfile != null)
  156. return classfile;
  157. if (readCounter++ > READ_THRESHOLD
  158. && ClassPool.releaseUnmodifiedClassFile) {
  159. releaseClassFiles();
  160. readCounter = 0;
  161. }
  162. InputStream fin = null;
  163. try {
  164. fin = classPool.openClassfile(getName());
  165. if (fin == null)
  166. throw new NotFoundException(getName());
  167. fin = new BufferedInputStream(fin);
  168. classfile = new ClassFile(new DataInputStream(fin));
  169. if (!classfile.getName().equals(qualifiedName))
  170. throw new RuntimeException("cannot find " + qualifiedName + ": "
  171. + classfile.getName() + " found in "
  172. + qualifiedName.replace('.', '/') + ".class");
  173. return classfile;
  174. }
  175. catch (NotFoundException e) {
  176. throw new RuntimeException(e.toString());
  177. }
  178. catch (IOException e) {
  179. throw new RuntimeException(e.toString());
  180. }
  181. finally {
  182. if (fin != null)
  183. try {
  184. fin.close();
  185. }
  186. catch (IOException e) {}
  187. }
  188. }
  189. /* Inherited from CtClass. Called by get() in ClassPool.
  190. *
  191. * @see javassist.CtClass#incGetCounter()
  192. */
  193. void incGetCounter() { ++getCounter; }
  194. /**
  195. * Releases the class files and cached CtBehaviors
  196. * of the CtClasses that have not been recently used
  197. * if they are unmodified.
  198. */
  199. private void releaseClassFiles() {
  200. Enumeration e = classPool.classes.elements();
  201. while (e.hasMoreElements()) {
  202. Object obj = e.nextElement();
  203. if (obj instanceof CtClassType) {
  204. CtClassType cct = (CtClassType)obj;
  205. if (cct.getCounter < 2 && !cct.isModified()) {
  206. cct.eraseCache();
  207. cct.classfile = null;
  208. }
  209. cct.getCounter = 0;
  210. }
  211. }
  212. }
  213. public ClassPool getClassPool() { return classPool; }
  214. void setClassPool(ClassPool cp) { classPool = cp; }
  215. public URL getURL() throws NotFoundException {
  216. URL url = classPool.find(getName());
  217. if (url == null)
  218. throw new NotFoundException(getName());
  219. else
  220. return url;
  221. }
  222. public boolean isModified() { return wasChanged; }
  223. public boolean isFrozen() { return wasFrozen; }
  224. void freeze() { wasFrozen = true; }
  225. void checkModify() throws RuntimeException {
  226. if (isFrozen()) {
  227. String msg = getName() + " class is frozen";
  228. if (wasPruned)
  229. msg += " and pruned";
  230. throw new RuntimeException(msg);
  231. }
  232. wasChanged = true;
  233. }
  234. public void defrost() {
  235. checkPruned("defrost");
  236. wasFrozen = false;
  237. }
  238. public boolean subtypeOf(CtClass clazz) throws NotFoundException {
  239. int i;
  240. String cname = clazz.getName();
  241. if (this == clazz || getName().equals(cname))
  242. return true;
  243. ClassFile file = getClassFile2();
  244. String supername = file.getSuperclass();
  245. if (supername != null && supername.equals(cname))
  246. return true;
  247. String[] ifs = file.getInterfaces();
  248. int num = ifs.length;
  249. for (i = 0; i < num; ++i)
  250. if (ifs[i].equals(cname))
  251. return true;
  252. if (supername != null && classPool.get(supername).subtypeOf(clazz))
  253. return true;
  254. for (i = 0; i < num; ++i)
  255. if (classPool.get(ifs[i]).subtypeOf(clazz))
  256. return true;
  257. return false;
  258. }
  259. public void setName(String name) throws RuntimeException {
  260. String oldname = getName();
  261. if (name.equals(oldname))
  262. return;
  263. // check this in advance although classNameChanged() below does.
  264. classPool.checkNotFrozen(name);
  265. ClassFile cf = getClassFile2();
  266. super.setName(name);
  267. cf.setName(name);
  268. eraseCache();
  269. classPool.classNameChanged(oldname, this);
  270. }
  271. public void replaceClassName(ClassMap classnames)
  272. throws RuntimeException
  273. {
  274. String oldClassName = getName();
  275. String newClassName
  276. = (String)classnames.get(Descriptor.toJvmName(oldClassName));
  277. if (newClassName != null) {
  278. newClassName = Descriptor.toJavaName(newClassName);
  279. // check this in advance although classNameChanged() below does.
  280. classPool.checkNotFrozen(newClassName);
  281. }
  282. super.replaceClassName(classnames);
  283. ClassFile cf = getClassFile2();
  284. cf.renameClass(classnames);
  285. eraseCache();
  286. if (newClassName != null) {
  287. super.setName(newClassName);
  288. classPool.classNameChanged(oldClassName, this);
  289. }
  290. }
  291. public void replaceClassName(String oldname, String newname)
  292. throws RuntimeException
  293. {
  294. String thisname = getName();
  295. if (thisname.equals(oldname))
  296. setName(newname);
  297. else {
  298. super.replaceClassName(oldname, newname);
  299. getClassFile2().renameClass(oldname, newname);
  300. eraseCache();
  301. }
  302. }
  303. public boolean isInterface() {
  304. return Modifier.isInterface(getModifiers());
  305. }
  306. public int getModifiers() {
  307. ClassFile cf = getClassFile2();
  308. int acc = cf.getAccessFlags();
  309. acc = AccessFlag.clear(acc, AccessFlag.SUPER);
  310. int inner = cf.getInnerAccessFlags();
  311. if (inner != -1 && (inner & AccessFlag.STATIC) != 0)
  312. acc |= AccessFlag.STATIC;
  313. return AccessFlag.toModifier(acc);
  314. }
  315. public void setModifiers(int mod) {
  316. if (Modifier.isStatic(mod))
  317. throw new RuntimeException("cannot set to static");
  318. checkModify();
  319. int acc = AccessFlag.of(mod) | AccessFlag.SUPER;
  320. getClassFile2().setAccessFlags(acc);
  321. }
  322. public Object[] getAnnotations() throws ClassNotFoundException {
  323. ClassFile cf = getClassFile2();
  324. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  325. cf.getAttribute(AnnotationsAttribute.invisibleTag);
  326. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  327. cf.getAttribute(AnnotationsAttribute.visibleTag);
  328. return toAnnotationType(getClassPool(), ainfo, ainfo2);
  329. }
  330. static Object[] toAnnotationType(ClassPool cp, AnnotationsAttribute a1,
  331. AnnotationsAttribute a2) throws ClassNotFoundException {
  332. Annotation[] anno1, anno2;
  333. int size1, size2;
  334. if (a1 == null) {
  335. anno1 = null;
  336. size1 = 0;
  337. }
  338. else {
  339. anno1 = a1.getAnnotations();
  340. size1 = anno1.length;
  341. }
  342. if (a2 == null) {
  343. anno2 = null;
  344. size2 = 0;
  345. }
  346. else {
  347. anno2 = a2.getAnnotations();
  348. size2 = anno2.length;
  349. }
  350. Object[] result = new Object[size1 + size2];
  351. ClassLoader cl = Thread.currentThread().getContextClassLoader();
  352. for (int i = 0; i < size1; i++)
  353. result[i] = anno1[i].toAnnotationType(cl, cp);
  354. for (int j = 0; j < size2; j++)
  355. result[j + size1] = anno2[j].toAnnotationType(cl, cp);
  356. return result;
  357. }
  358. static Object[][] toAnnotationType(ClassPool cp, ParameterAnnotationsAttribute a1,
  359. ParameterAnnotationsAttribute a2) throws ClassNotFoundException {
  360. int numParameters = 0;
  361. if (a1 != null)
  362. numParameters = a1.numParameters();
  363. else
  364. numParameters = a2.numParameters();
  365. Object[][] result = new Object[numParameters][];
  366. ClassLoader cl = Thread.currentThread().getContextClassLoader();
  367. for (int i = 0; i < numParameters; i++) {
  368. Annotation[] anno1, anno2;
  369. int size1, size2;
  370. if (a1 == null) {
  371. anno1 = null;
  372. size1 = 0;
  373. }
  374. else {
  375. anno1 = a1.getAnnotations()[i];
  376. size1 = anno1.length;
  377. }
  378. if (a2 == null) {
  379. anno2 = null;
  380. size2 = 0;
  381. }
  382. else {
  383. anno2 = a2.getAnnotations()[i];
  384. size2 = anno2.length;
  385. }
  386. result[i] = new Object[size1 + size2];
  387. for (int j = 0; j < size1; ++j)
  388. result[i][j] = anno1[j].toAnnotationType(cl, cp);
  389. for (int j = 0; j < size2; ++j)
  390. result[i][j + size1] = anno2[j].toAnnotationType(cl, cp);
  391. }
  392. return result;
  393. }
  394. public boolean subclassOf(CtClass superclass) {
  395. if (superclass == null)
  396. return false;
  397. String superName = superclass.getName();
  398. CtClass curr = this;
  399. try {
  400. while (curr != null) {
  401. if (curr.getName().equals(superName))
  402. return true;
  403. curr = curr.getSuperclass();
  404. }
  405. }
  406. catch (Exception ignored) {}
  407. return false;
  408. }
  409. public CtClass getSuperclass() throws NotFoundException {
  410. String supername = getClassFile2().getSuperclass();
  411. if (supername == null)
  412. return null;
  413. else
  414. return classPool.get(supername);
  415. }
  416. public void setSuperclass(CtClass clazz) throws CannotCompileException {
  417. checkModify();
  418. if (isInterface())
  419. addInterface(clazz);
  420. else
  421. getClassFile2().setSuperclass(clazz.getName());
  422. }
  423. public CtClass[] getInterfaces() throws NotFoundException {
  424. String[] ifs = getClassFile2().getInterfaces();
  425. int num = ifs.length;
  426. CtClass[] ifc = new CtClass[num];
  427. for (int i = 0; i < num; ++i)
  428. ifc[i] = classPool.get(ifs[i]);
  429. return ifc;
  430. }
  431. public void setInterfaces(CtClass[] list) {
  432. checkModify();
  433. String[] ifs;
  434. if (list == null)
  435. ifs = new String[0];
  436. else {
  437. int num = list.length;
  438. ifs = new String[num];
  439. for (int i = 0; i < num; ++i)
  440. ifs[i] = list[i].getName();
  441. }
  442. getClassFile2().setInterfaces(ifs);
  443. }
  444. public void addInterface(CtClass anInterface) {
  445. checkModify();
  446. if (anInterface != null)
  447. getClassFile2().addInterface(anInterface.getName());
  448. }
  449. public CtClass getDeclaringClass() throws NotFoundException {
  450. ClassFile cf = getClassFile2();
  451. InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
  452. InnerClassesAttribute.tag);
  453. if (ica == null)
  454. return null;
  455. String name = getName();
  456. int n = ica.tableLength();
  457. for (int i = 0; i < n; ++i)
  458. if (name.equals(ica.innerClass(i))) {
  459. String outName = ica.outerClass(i);
  460. if (outName != null)
  461. return classPool.get(outName);
  462. else {
  463. // maybe anonymous or local class.
  464. EnclosingMethodAttribute ema
  465. = (EnclosingMethodAttribute)cf.getAttribute(
  466. EnclosingMethodAttribute.tag);
  467. if (ema != null)
  468. return classPool.get(ema.className());
  469. }
  470. }
  471. return null;
  472. }
  473. public CtMethod getEnclosingMethod() throws NotFoundException {
  474. ClassFile cf = getClassFile2();
  475. EnclosingMethodAttribute ema
  476. = (EnclosingMethodAttribute)cf.getAttribute(
  477. EnclosingMethodAttribute.tag);
  478. if (ema != null) {
  479. CtClass enc = classPool.get(ema.className());
  480. return enc.getMethod(ema.methodName(), ema.methodDescriptor());
  481. }
  482. return null;
  483. }
  484. public CtClass makeNestedClass(String name, boolean isStatic) {
  485. if (!isStatic)
  486. throw new RuntimeException(
  487. "sorry, only nested static class is supported");
  488. checkModify();
  489. CtClass c = classPool.makeNestedClass(getName() + "$" + name);
  490. ClassFile cf = getClassFile2();
  491. ClassFile cf2 = c.getClassFile2();
  492. InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
  493. InnerClassesAttribute.tag);
  494. if (ica == null) {
  495. ica = new InnerClassesAttribute(cf.getConstPool());
  496. cf.addAttribute(ica);
  497. }
  498. ica.append(c.getName(), this.getName(), name,
  499. (cf2.getAccessFlags() & ~AccessFlag.SUPER) | AccessFlag.STATIC);
  500. cf2.addAttribute(ica.copy(cf2.getConstPool(), null));
  501. return c;
  502. }
  503. public CtField[] getFields() {
  504. ArrayList alist = new ArrayList();
  505. getFields(alist, this);
  506. return (CtField[])alist.toArray(new CtField[alist.size()]);
  507. }
  508. private static void getFields(ArrayList alist, CtClass cc) {
  509. int i, num;
  510. if (cc == null)
  511. return;
  512. try {
  513. getFields(alist, cc.getSuperclass());
  514. }
  515. catch (NotFoundException e) {}
  516. try {
  517. CtClass[] ifs = cc.getInterfaces();
  518. num = ifs.length;
  519. for (i = 0; i < num; ++i)
  520. getFields(alist, ifs[i]);
  521. }
  522. catch (NotFoundException e) {}
  523. CtMember cf = ((CtClassType)cc).getFieldsCache();
  524. while (cf != null) {
  525. if (!Modifier.isPrivate(cf.getModifiers()))
  526. alist.add(cf);
  527. cf = cf.next;
  528. }
  529. }
  530. public CtField getField(String name) throws NotFoundException {
  531. CtField f = getField2(name);
  532. if (f == null)
  533. throw new NotFoundException("field: " + name + " in " + getName());
  534. else
  535. return f;
  536. }
  537. CtField getField2(String name) {
  538. CtField df = getDeclaredField2(name);
  539. if (df != null)
  540. return df;
  541. try {
  542. CtClass[] ifs = getInterfaces();
  543. int num = ifs.length;
  544. for (int i = 0; i < num; ++i) {
  545. CtField f = ifs[i].getField2(name);
  546. if (f != null)
  547. return f;
  548. }
  549. CtClass s = getSuperclass();
  550. if (s != null)
  551. return s.getField2(name);
  552. }
  553. catch (NotFoundException e) {}
  554. return null;
  555. }
  556. public CtField[] getDeclaredFields() {
  557. CtMember cf = getFieldsCache();
  558. int num = CtField.count(cf);
  559. CtField[] cfs = new CtField[num];
  560. int i = 0;
  561. while (cf != null) {
  562. cfs[i++] = (CtField)cf;
  563. cf = cf.next;
  564. }
  565. return cfs;
  566. }
  567. protected CtMember getFieldsCache() {
  568. if (fieldsCache == null) {
  569. List list = getClassFile2().getFields();
  570. int n = list.size();
  571. CtMember allFields = null;
  572. CtField tail = null;
  573. for (int i = 0; i < n; ++i) {
  574. FieldInfo finfo = (FieldInfo)list.get(i);
  575. CtField newTail = new CtField(finfo, this);
  576. allFields = CtMember.append(allFields, tail, newTail);
  577. tail = newTail;
  578. }
  579. fieldsCache = allFields;
  580. }
  581. return fieldsCache;
  582. }
  583. public CtField getDeclaredField(String name) throws NotFoundException {
  584. CtField f = getDeclaredField2(name);
  585. if (f == null)
  586. throw new NotFoundException("field: " + name + " in " + getName());
  587. else
  588. return f;
  589. }
  590. private CtField getDeclaredField2(String name) {
  591. CtMember cf = getFieldsCache();
  592. while (cf != null) {
  593. if (cf.getName().equals(name))
  594. return (CtField)cf;
  595. cf = cf.next;
  596. }
  597. return null;
  598. }
  599. public CtBehavior[] getDeclaredBehaviors() {
  600. CtMember cc = getConstructorsCache();
  601. CtMember cm = getMethodsCache();
  602. int num = CtMember.count(cm) + CtMember.count(cc);
  603. CtBehavior[] cb = new CtBehavior[num];
  604. int i = 0;
  605. while (cc != null) {
  606. cb[i++] = (CtBehavior)cc;
  607. cc = cc.next;
  608. }
  609. while (cm != null) {
  610. cb[i++] = (CtBehavior)cm;
  611. cm = cm.next;
  612. }
  613. return cb;
  614. }
  615. public CtConstructor[] getConstructors() {
  616. CtConstructor[] cons = getDeclaredConstructors();
  617. if (cons.length == 0)
  618. return cons;
  619. int n = 0;
  620. int i = cons.length;
  621. while (--i >= 0)
  622. if (!Modifier.isPrivate(cons[i].getModifiers()))
  623. ++n;
  624. CtConstructor[] result = new CtConstructor[n];
  625. n = 0;
  626. i = cons.length;
  627. while (--i >= 0) {
  628. CtConstructor c = cons[i];
  629. if (!Modifier.isPrivate(c.getModifiers()))
  630. result[n++] = c;
  631. }
  632. return result;
  633. }
  634. public CtConstructor getConstructor(String desc)
  635. throws NotFoundException
  636. {
  637. CtConstructor cc = (CtConstructor)getConstructorsCache();
  638. while (cc != null) {
  639. if (cc.getMethodInfo2().getDescriptor().equals(desc))
  640. return cc;
  641. cc = (CtConstructor)cc.next;
  642. }
  643. return super.getConstructor(desc);
  644. }
  645. public CtConstructor[] getDeclaredConstructors() {
  646. CtMember cc = getConstructorsCache();
  647. int num = CtMember.count(cc);
  648. CtConstructor[] ccs = new CtConstructor[num];
  649. int i = 0;
  650. while (cc != null) {
  651. ccs[i++] = (CtConstructor)cc;
  652. cc = cc.next;
  653. }
  654. return ccs;
  655. }
  656. protected CtMember getConstructorsCache() {
  657. if (constructorsCache == null) {
  658. List list = getClassFile2().getMethods();
  659. int n = list.size();
  660. CtMember allConstructors = null;
  661. CtConstructor tail = null;
  662. for (int i = 0; i < n; ++i) {
  663. MethodInfo minfo = (MethodInfo)list.get(i);
  664. if (minfo.isConstructor()) {
  665. CtConstructor newTail = new CtConstructor(minfo, this);
  666. allConstructors = CtMember.append(allConstructors, tail, newTail);
  667. tail = newTail;
  668. }
  669. }
  670. constructorsCache = allConstructors;
  671. }
  672. return constructorsCache;
  673. }
  674. public CtConstructor getClassInitializer() {
  675. if (classInitializerCache == null) {
  676. MethodInfo minfo = getClassFile2().getStaticInitializer();
  677. if (minfo != null)
  678. classInitializerCache = new CtConstructor(minfo, this);
  679. }
  680. return classInitializerCache;
  681. }
  682. public CtMethod[] getMethods() {
  683. HashMap h = new HashMap();
  684. getMethods0(h, this);
  685. return (CtMethod[])h.values().toArray(new CtMethod[h.size()]);
  686. }
  687. private static void getMethods0(HashMap h, CtClass cc) {
  688. try {
  689. CtClass[] ifs = cc.getInterfaces();
  690. int size = ifs.length;
  691. for (int i = 0; i < size; ++i)
  692. getMethods0(h, ifs[i]);
  693. }
  694. catch (NotFoundException e) {}
  695. try {
  696. CtClass s = cc.getSuperclass();
  697. if (s != null)
  698. getMethods0(h, s);
  699. }
  700. catch (NotFoundException e) {}
  701. if (cc instanceof CtClassType) {
  702. CtMember cm = ((CtClassType)cc).getMethodsCache();
  703. while (cm != null) {
  704. if (!Modifier.isPrivate(cm.getModifiers()))
  705. h.put(((CtMethod)cm).getStringRep(), cm);
  706. cm = cm.next;
  707. }
  708. }
  709. }
  710. public CtMethod getMethod(String name, String desc)
  711. throws NotFoundException
  712. {
  713. CtMethod m = getMethod0(this, name, desc);
  714. if (m != null)
  715. return m;
  716. else
  717. throw new NotFoundException(name + "(..) is not found in "
  718. + getName());
  719. }
  720. private static CtMethod getMethod0(CtClass cc,
  721. String name, String desc) {
  722. if (cc instanceof CtClassType) {
  723. CtMethod cm = (CtMethod)((CtClassType)cc).getMethodsCache();
  724. while (cm != null) {
  725. if (cm.getName().equals(name)
  726. && cm.getMethodInfo2().getDescriptor().equals(desc))
  727. return cm;
  728. cm = (CtMethod)cm.next;
  729. }
  730. }
  731. try {
  732. CtClass s = cc.getSuperclass();
  733. if (s != null) {
  734. CtMethod m = getMethod0(s, name, desc);
  735. if (m != null)
  736. return m;
  737. }
  738. }
  739. catch (NotFoundException e) {}
  740. try {
  741. CtClass[] ifs = cc.getInterfaces();
  742. int size = ifs.length;
  743. for (int i = 0; i < size; ++i) {
  744. CtMethod m = getMethod0(ifs[i], name, desc);
  745. if (m != null)
  746. return m;
  747. }
  748. }
  749. catch (NotFoundException e) {}
  750. return null;
  751. }
  752. public CtMethod[] getDeclaredMethods() {
  753. CtMember cm = getMethodsCache();
  754. int num = CtMember.count(cm);
  755. CtMethod[] cms = new CtMethod[num];
  756. int i = 0;
  757. while (cm != null) {
  758. cms[i++] = (CtMethod)cm;
  759. cm = cm.next;
  760. }
  761. return cms;
  762. }
  763. public CtMethod getDeclaredMethod(String name) throws NotFoundException {
  764. CtMember m = getMethodsCache();
  765. while (m != null) {
  766. if (m.getName().equals(name))
  767. return (CtMethod)m;
  768. m = m.next;
  769. }
  770. throw new NotFoundException(name + "(..) is not found in "
  771. + getName());
  772. }
  773. public CtMethod getDeclaredMethod(String name, CtClass[] params)
  774. throws NotFoundException
  775. {
  776. String desc = Descriptor.ofParameters(params);
  777. CtMethod m = (CtMethod)getMethodsCache();
  778. while (m != null) {
  779. if (m.getName().equals(name)
  780. && m.getMethodInfo2().getDescriptor().startsWith(desc))
  781. return m;
  782. m = (CtMethod)m.next;
  783. }
  784. throw new NotFoundException(name + "(..) is not found in "
  785. + getName());
  786. }
  787. protected CtMember getMethodsCache() {
  788. if (methodsCache == null) {
  789. List list = getClassFile2().getMethods();
  790. int n = list.size();
  791. CtMember allMethods = null;
  792. CtMethod tail = null;
  793. for (int i = 0; i < n; ++i) {
  794. MethodInfo minfo = (MethodInfo)list.get(i);
  795. if (minfo.isMethod()) {
  796. CtMethod newTail = new CtMethod(minfo, this);
  797. allMethods = CtMember.append(allMethods, tail, newTail);
  798. tail = newTail;
  799. }
  800. }
  801. methodsCache = allMethods;
  802. }
  803. return methodsCache;
  804. }
  805. public void addField(CtField f, String init)
  806. throws CannotCompileException
  807. {
  808. addField(f, CtField.Initializer.byExpr(init));
  809. }
  810. public void addField(CtField f, CtField.Initializer init)
  811. throws CannotCompileException
  812. {
  813. checkModify();
  814. if (f.getDeclaringClass() != this)
  815. throw new CannotCompileException("cannot add");
  816. if (init == null)
  817. init = f.getInit();
  818. if (init != null) {
  819. int mod = f.getModifiers();
  820. if (Modifier.isStatic(mod) && Modifier.isFinal(mod))
  821. try {
  822. ConstPool cp = getClassFile2().getConstPool();
  823. int index = init.getConstantValue(cp, f.getType());
  824. if (index != 0) {
  825. f.getFieldInfo2().addAttribute(new ConstantAttribute(cp, index));
  826. init = null;
  827. }
  828. }
  829. catch (NotFoundException e) {}
  830. }
  831. getFieldsCache();
  832. fieldsCache = CtField.append(fieldsCache, f);
  833. getClassFile2().addField(f.getFieldInfo2());
  834. if (init != null) {
  835. FieldInitLink fil = new FieldInitLink(f, init);
  836. FieldInitLink link = fieldInitializers;
  837. if (link == null)
  838. fieldInitializers = fil;
  839. else {
  840. while (link.next != null)
  841. link = link.next;
  842. link.next = fil;
  843. }
  844. }
  845. }
  846. public void removeField(CtField f) throws NotFoundException {
  847. checkModify();
  848. FieldInfo fi = f.getFieldInfo2();
  849. ClassFile cf = getClassFile2();
  850. if (cf.getFields().remove(fi)) {
  851. fieldsCache = CtMember.remove(fieldsCache, f);
  852. memberRemoved = true;
  853. }
  854. else
  855. throw new NotFoundException(f.toString());
  856. }
  857. public CtConstructor makeClassInitializer()
  858. throws CannotCompileException
  859. {
  860. CtConstructor clinit = getClassInitializer();
  861. if (clinit != null)
  862. return clinit;
  863. checkModify();
  864. ClassFile cf = getClassFile2();
  865. Bytecode code = new Bytecode(cf.getConstPool(), 0, 0);
  866. modifyClassConstructor(cf, code, 0, 0);
  867. return getClassInitializer();
  868. }
  869. public void addConstructor(CtConstructor c)
  870. throws CannotCompileException
  871. {
  872. checkModify();
  873. if (c.getDeclaringClass() != this)
  874. throw new CannotCompileException("cannot add");
  875. getConstructorsCache();
  876. constructorsCache = (CtConstructor)CtMember.append(constructorsCache, c);
  877. getClassFile2().addMethod(c.getMethodInfo2());
  878. }
  879. public void removeConstructor(CtConstructor m) throws NotFoundException {
  880. checkModify();
  881. MethodInfo mi = m.getMethodInfo2();
  882. ClassFile cf = getClassFile2();
  883. if (cf.getMethods().remove(mi)) {
  884. constructorsCache = CtMember.remove(constructorsCache, m);
  885. memberRemoved = true;
  886. }
  887. else
  888. throw new NotFoundException(m.toString());
  889. }
  890. public void addMethod(CtMethod m) throws CannotCompileException {
  891. checkModify();
  892. if (m.getDeclaringClass() != this)
  893. throw new CannotCompileException("cannot add");
  894. getMethodsCache();
  895. methodsCache = CtMember.append(methodsCache, m);
  896. getClassFile2().addMethod(m.getMethodInfo2());
  897. if ((m.getModifiers() & Modifier.ABSTRACT) != 0)
  898. setModifiers(getModifiers() | Modifier.ABSTRACT);
  899. }
  900. public void removeMethod(CtMethod m) throws NotFoundException {
  901. checkModify();
  902. MethodInfo mi = m.getMethodInfo2();
  903. ClassFile cf = getClassFile2();
  904. if (cf.getMethods().remove(mi)) {
  905. methodsCache = CtMember.remove(methodsCache, m);
  906. memberRemoved = true;
  907. }
  908. else
  909. throw new NotFoundException(m.toString());
  910. }
  911. public byte[] getAttribute(String name) {
  912. AttributeInfo ai = getClassFile2().getAttribute(name);
  913. if (ai == null)
  914. return null;
  915. else
  916. return ai.get();
  917. }
  918. public void setAttribute(String name, byte[] data) {
  919. checkModify();
  920. ClassFile cf = getClassFile2();
  921. cf.addAttribute(new AttributeInfo(cf.getConstPool(), name, data));
  922. }
  923. public void instrument(CodeConverter converter)
  924. throws CannotCompileException
  925. {
  926. checkModify();
  927. ClassFile cf = getClassFile2();
  928. ConstPool cp = cf.getConstPool();
  929. List list = cf.getMethods();
  930. int n = list.size();
  931. for (int i = 0; i < n; ++i) {
  932. MethodInfo minfo = (MethodInfo)list.get(i);
  933. converter.doit(this, minfo, cp);
  934. }
  935. }
  936. public void instrument(ExprEditor editor)
  937. throws CannotCompileException
  938. {
  939. checkModify();
  940. ClassFile cf = getClassFile2();
  941. List list = cf.getMethods();
  942. int n = list.size();
  943. for (int i = 0; i < n; ++i) {
  944. MethodInfo minfo = (MethodInfo)list.get(i);
  945. editor.doit(this, minfo);
  946. }
  947. }
  948. /**
  949. * @see javassist.CtClass#prune()
  950. * @see javassist.CtClass#stopPruning(boolean)
  951. */
  952. public void prune() {
  953. if (wasPruned)
  954. return;
  955. wasPruned = wasFrozen = true;
  956. getClassFile2().prune();
  957. }
  958. public void toBytecode(DataOutputStream out)
  959. throws CannotCompileException, IOException
  960. {
  961. try {
  962. if (isModified()) {
  963. checkPruned("toBytecode");
  964. ClassFile cf = getClassFile2();
  965. if (memberRemoved) {
  966. cf.compact();
  967. memberRemoved = false;
  968. }
  969. modifyClassConstructor(cf);
  970. modifyConstructors(cf);
  971. cf.write(out);
  972. out.flush();
  973. fieldInitializers = null;
  974. if (doPruning) {
  975. // to save memory
  976. cf.prune();
  977. wasPruned = true;
  978. }
  979. }
  980. else {
  981. classPool.writeClassfile(getName(), out);
  982. // to save memory
  983. eraseCache();
  984. classfile = null;
  985. }
  986. wasFrozen = true;
  987. }
  988. catch (NotFoundException e) {
  989. throw new CannotCompileException(e);
  990. }
  991. catch (IOException e) {
  992. throw new CannotCompileException(e);
  993. }
  994. }
  995. /* See also checkModified()
  996. */
  997. private void checkPruned(String method) {
  998. if (wasPruned)
  999. throw new RuntimeException(method + "(): " + getName()
  1000. + " was pruned.");
  1001. }
  1002. public boolean stopPruning(boolean stop) {
  1003. boolean prev = !doPruning;
  1004. doPruning = !stop;
  1005. return prev;
  1006. }
  1007. private void modifyClassConstructor(ClassFile cf)
  1008. throws CannotCompileException, NotFoundException
  1009. {
  1010. if (fieldInitializers == null)
  1011. return;
  1012. Bytecode code = new Bytecode(cf.getConstPool(), 0, 0);
  1013. Javac jv = new Javac(code, this);
  1014. int stacksize = 0;
  1015. boolean doInit = false;
  1016. for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) {
  1017. CtField f = fi.field;
  1018. if (Modifier.isStatic(f.getModifiers())) {
  1019. doInit = true;
  1020. int s = fi.init.compileIfStatic(f.getType(), f.getName(),
  1021. code, jv);
  1022. if (stacksize < s)
  1023. stacksize = s;
  1024. }
  1025. }
  1026. if (doInit) // need an initializer for static fileds.
  1027. modifyClassConstructor(cf, code, stacksize, 0);
  1028. }
  1029. private void modifyClassConstructor(ClassFile cf, Bytecode code,
  1030. int stacksize, int localsize)
  1031. throws CannotCompileException
  1032. {
  1033. MethodInfo m = cf.getStaticInitializer();
  1034. if (m == null) {
  1035. code.add(Bytecode.RETURN);
  1036. code.setMaxStack(stacksize);
  1037. code.setMaxLocals(localsize);
  1038. m = new MethodInfo(cf.getConstPool(), "<clinit>", "()V");
  1039. m.setAccessFlags(AccessFlag.STATIC);
  1040. m.setCodeAttribute(code.toCodeAttribute());
  1041. cf.addMethod(m);
  1042. }
  1043. else {
  1044. CodeAttribute codeAttr = m.getCodeAttribute();
  1045. if (codeAttr == null)
  1046. throw new CannotCompileException("empty <clinit>");
  1047. try {
  1048. CodeIterator it = codeAttr.iterator();
  1049. int pos = it.insertEx(code.get());
  1050. it.insert(code.getExceptionTable(), pos);
  1051. int maxstack = codeAttr.getMaxStack();
  1052. if (maxstack < stacksize)
  1053. codeAttr.setMaxStack(stacksize);
  1054. int maxlocals = codeAttr.getMaxLocals();
  1055. if (maxlocals < localsize)
  1056. codeAttr.setMaxLocals(localsize);
  1057. }
  1058. catch (BadBytecode e) {
  1059. throw new CannotCompileException(e);
  1060. }
  1061. }
  1062. }
  1063. private void modifyConstructors(ClassFile cf)
  1064. throws CannotCompileException, NotFoundException
  1065. {
  1066. if (fieldInitializers == null)
  1067. return;
  1068. ConstPool cp = cf.getConstPool();
  1069. List list = cf.getMethods();
  1070. int n = list.size();
  1071. for (int i = 0; i < n; ++i) {
  1072. MethodInfo minfo = (MethodInfo)list.get(i);
  1073. if (minfo.isConstructor()) {
  1074. CodeAttribute codeAttr = minfo.getCodeAttribute();
  1075. if (codeAttr != null)
  1076. try {
  1077. Bytecode init = new Bytecode(cp, 0,
  1078. codeAttr.getMaxLocals());
  1079. CtClass[] params
  1080. = Descriptor.getParameterTypes(
  1081. minfo.getDescriptor(),
  1082. classPool);
  1083. int stacksize = makeFieldInitializer(init, params);
  1084. insertAuxInitializer(codeAttr, init, stacksize);
  1085. }
  1086. catch (BadBytecode e) {
  1087. throw new CannotCompileException(e);
  1088. }
  1089. }
  1090. }
  1091. }
  1092. private static void insertAuxInitializer(CodeAttribute codeAttr,
  1093. Bytecode initializer,
  1094. int stacksize)
  1095. throws BadBytecode
  1096. {
  1097. CodeIterator it = codeAttr.iterator();
  1098. int index = it.skipSuperConstructor();
  1099. if (index < 0) {
  1100. index = it.skipThisConstructor();
  1101. if (index >= 0)
  1102. return; // this() is called.
  1103. // Neither this() or super() is called.
  1104. }
  1105. int pos = it.insertEx(initializer.get());
  1106. it.insert(initializer.getExceptionTable(), pos);
  1107. int maxstack = codeAttr.getMaxStack();
  1108. if (maxstack < stacksize)
  1109. codeAttr.setMaxStack(stacksize);
  1110. }
  1111. private int makeFieldInitializer(Bytecode code, CtClass[] parameters)
  1112. throws CannotCompileException, NotFoundException
  1113. {
  1114. int stacksize = 0;
  1115. Javac jv = new Javac(code, this);
  1116. try {
  1117. jv.recordParams(parameters, false);
  1118. }
  1119. catch (CompileError e) {
  1120. throw new CannotCompileException(e);
  1121. }
  1122. for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) {
  1123. CtField f = fi.field;
  1124. if (!Modifier.isStatic(f.getModifiers())) {
  1125. int s = fi.init.compile(f.getType(), f.getName(), code,
  1126. parameters, jv);
  1127. if (stacksize < s)
  1128. stacksize = s;
  1129. }
  1130. }
  1131. return stacksize;
  1132. }
  1133. // Methods used by CtNewWrappedMethod
  1134. Hashtable getHiddenMethods() {
  1135. if (hiddenMethods == null)
  1136. hiddenMethods = new Hashtable();
  1137. return hiddenMethods;
  1138. }
  1139. int getUniqueNumber() { return uniqueNumberSeed++; }
  1140. public String makeUniqueName(String prefix) {
  1141. HashMap table = new HashMap();
  1142. makeMemberList(table);
  1143. Set keys = table.keySet();
  1144. String[] methods = new String[keys.size()];
  1145. keys.toArray(methods);
  1146. if (notFindInArray(prefix, methods))
  1147. return prefix;
  1148. int i = 100;
  1149. String name;
  1150. do {
  1151. if (i > 999)
  1152. throw new RuntimeException("too many unique name");
  1153. name = prefix + i++;
  1154. } while (!notFindInArray(name, methods));
  1155. return name;
  1156. }
  1157. private static boolean notFindInArray(String prefix, String[] values) {
  1158. int len = values.length;
  1159. for (int i = 0; i < len; i++)
  1160. if (values[i].startsWith(prefix))
  1161. return false;
  1162. return true;
  1163. }
  1164. private void makeMemberList(HashMap table) {
  1165. int mod = getModifiers();
  1166. if (Modifier.isAbstract(mod) || Modifier.isInterface(mod))
  1167. try {
  1168. CtClass[] ifs = getInterfaces();
  1169. int size = ifs.length;
  1170. for (int i = 0; i < size; i++) {
  1171. CtClass ic =ifs[i];
  1172. if (ic != null && ic instanceof CtClassType)
  1173. ((CtClassType)ic).makeMemberList(table);
  1174. }
  1175. }
  1176. catch (NotFoundException e) {}
  1177. try {
  1178. CtClass s = getSuperclass();
  1179. if (s != null && s instanceof CtClassType)
  1180. ((CtClassType)s).makeMemberList(table);
  1181. }
  1182. catch (NotFoundException e) {}
  1183. List list = getClassFile2().getMethods();
  1184. int n = list.size();
  1185. for (int i = 0; i < n; i++) {
  1186. MethodInfo minfo = (MethodInfo)list.get(i);
  1187. table.put(minfo.getName(), this);
  1188. }
  1189. list = getClassFile2().getFields();
  1190. n = list.size();
  1191. for (int i = 0; i < n; i++) {
  1192. FieldInfo finfo = (FieldInfo)list.get(i);
  1193. table.put(finfo.getName(), this);
  1194. }
  1195. }
  1196. }
  1197. class FieldInitLink {
  1198. FieldInitLink next;
  1199. CtField field;
  1200. CtField.Initializer init;
  1201. FieldInitLink(CtField f, CtField.Initializer i) {
  1202. next = null;
  1203. field = f;
  1204. init = i;
  1205. }
  1206. }