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.

ClassFile.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2004 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.bytecode;
  16. import java.io.DataInputStream;
  17. import java.io.DataOutputStream;
  18. import java.io.IOException;
  19. import java.util.Map;
  20. import java.util.LinkedList;
  21. import java.util.ListIterator;
  22. import java.util.List;
  23. import javassist.CannotCompileException;
  24. import javassist.bytecode.annotation.AnnotationGroup;
  25. /**
  26. * <code>ClassFile</code> represents a Java <code>.class</code> file,
  27. * which consists of a constant pool, methods, fields, and attributes.
  28. *
  29. * @see javassist.CtClass#getClassFile()
  30. */
  31. public final class ClassFile {
  32. ConstPool constPool;
  33. int thisClass;
  34. int accessFlags;
  35. int superClass;
  36. int[] interfaces;
  37. LinkedList fields;
  38. LinkedList methods;
  39. LinkedList attributes;
  40. AnnotationGroup runtimeInvisible;
  41. AnnotationGroup runtimeVisible;
  42. String thisclassname; // not JVM-internal name
  43. /**
  44. * Constructs a class file from a byte stream.
  45. */
  46. public ClassFile(DataInputStream in) throws IOException {
  47. read(in);
  48. }
  49. /**
  50. * Constructs a class file including no members.
  51. *
  52. * @param isInterface true if this is an interface.
  53. * false if this is a class.
  54. * @param classname a fully-qualified class name
  55. * @param superclass a fully-qualified super class name
  56. */
  57. public ClassFile(boolean isInterface,
  58. String classname, String superclass) {
  59. constPool = new ConstPool(classname);
  60. thisClass = constPool.getThisClassInfo();
  61. if (isInterface)
  62. accessFlags = AccessFlag.SUPER | AccessFlag.INTERFACE
  63. | AccessFlag.ABSTRACT;
  64. else
  65. accessFlags = AccessFlag.SUPER;
  66. initSuperclass(superclass);
  67. interfaces = null;
  68. fields = new LinkedList();
  69. methods = new LinkedList();
  70. thisclassname = classname;
  71. attributes = new LinkedList();
  72. attributes.add(new SourceFileAttribute(constPool,
  73. getSourcefileName(thisclassname)));
  74. }
  75. private void initSuperclass(String superclass) {
  76. if (superclass != null)
  77. superClass = constPool.addClassInfo(superclass);
  78. else
  79. superClass = constPool.addClassInfo("java.lang.Object");
  80. }
  81. private static String getSourcefileName(String qname) {
  82. int index = qname.lastIndexOf('.');
  83. if (index >= 0)
  84. qname = qname.substring(index + 1);
  85. return qname + ".java";
  86. }
  87. /**
  88. * Returns a constant pool table.
  89. */
  90. public ConstPool getConstPool() {
  91. return constPool;
  92. }
  93. /**
  94. * Returns true if this is an interface.
  95. */
  96. public boolean isInterface() {
  97. return (accessFlags & AccessFlag.INTERFACE) != 0;
  98. }
  99. /**
  100. * Returns true if this is a final class or interface.
  101. */
  102. public boolean isFinal() {
  103. return (accessFlags & AccessFlag.FINAL) != 0;
  104. }
  105. /**
  106. * Returns true if this is an abstract class or an interface.
  107. */
  108. public boolean isAbstract() {
  109. return (accessFlags & AccessFlag.ABSTRACT) != 0;
  110. }
  111. /**
  112. * Returns access flags.
  113. *
  114. * @see javassist.bytecode.AccessFlag
  115. */
  116. public int getAccessFlags() {
  117. return accessFlags;
  118. }
  119. /**
  120. * Changes access flags.
  121. *
  122. * @see javassist.bytecode.AccessFlag
  123. */
  124. public void setAccessFlags(int acc) {
  125. accessFlags = acc | AccessFlag.SUPER;
  126. }
  127. /**
  128. * Returns the class name.
  129. */
  130. public String getName() {
  131. return thisclassname;
  132. }
  133. /**
  134. * Sets the class name. This method substitutes the new name
  135. * for all occurrences of the old class name in the class file.
  136. */
  137. public void setName(String name) {
  138. renameClass(thisclassname, name);
  139. }
  140. /**
  141. * Returns the super class name.
  142. */
  143. public String getSuperclass() {
  144. return constPool.getClassInfo(superClass);
  145. }
  146. /**
  147. * Returns the index of the constant pool entry representing
  148. * the super class.
  149. */
  150. public int getSuperclassId() {
  151. return superClass;
  152. }
  153. /**
  154. * Sets the super class.
  155. *
  156. * <p>This method modifies constructors so that they call
  157. * constructors declared in the new super class.
  158. */
  159. public void setSuperclass(String superclass)
  160. throws CannotCompileException
  161. {
  162. if (superclass == null)
  163. superclass = "java.lang.Object";
  164. try {
  165. superClass = constPool.addClassInfo(superclass);
  166. LinkedList list = methods;
  167. int n = list.size();
  168. for (int i = 0; i < n; ++i) {
  169. MethodInfo minfo = (MethodInfo)list.get(i);
  170. minfo.setSuperclass(superclass);
  171. }
  172. }
  173. catch (BadBytecode e) {
  174. throw new CannotCompileException(e);
  175. }
  176. }
  177. /**
  178. * Replaces all occurrences of a class name in the class file.
  179. *
  180. * <p>If class X is substituted for class Y in the class file,
  181. * X and Y must have the same signature. If Y provides a method
  182. * m(), X must provide it even if X inherits m() from the super class.
  183. * If this fact is not guaranteed, the bytecode verifier may cause
  184. * an error.
  185. *
  186. * @param oldname the replaced class name
  187. * @param newname the substituted class name
  188. */
  189. public final void renameClass(String oldname, String newname) {
  190. LinkedList list;
  191. int n;
  192. if (oldname.equals(newname))
  193. return;
  194. if (oldname.equals(thisclassname))
  195. thisclassname = newname;
  196. oldname = Descriptor.toJvmName(oldname);
  197. newname = Descriptor.toJvmName(newname);
  198. constPool.renameClass(oldname, newname);
  199. list = methods;
  200. n = list.size();
  201. for (int i = 0; i < n; ++i) {
  202. MethodInfo minfo = (MethodInfo)list.get(i);
  203. String desc = minfo.getDescriptor();
  204. minfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
  205. }
  206. list = fields;
  207. n = list.size();
  208. for (int i = 0; i < n; ++i) {
  209. FieldInfo finfo = (FieldInfo)list.get(i);
  210. String desc = finfo.getDescriptor();
  211. finfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
  212. }
  213. }
  214. /**
  215. * Replaces all occurrences of several class names in the class file.
  216. *
  217. * @param classnames specifies which class name is replaced
  218. * with which new name. Class names must
  219. * be described with the JVM-internal
  220. * representation like
  221. * <code>java/lang/Object</code>.
  222. *
  223. * @see #renameClass(String,String)
  224. */
  225. public final void renameClass(Map classnames) {
  226. String jvmNewThisName
  227. = (String)classnames.get(Descriptor.toJvmName(thisclassname));
  228. if (jvmNewThisName != null)
  229. thisclassname = Descriptor.toJavaName(jvmNewThisName);
  230. constPool.renameClass(classnames);
  231. LinkedList list = methods;
  232. int n = list.size();
  233. for (int i = 0; i < n; ++i) {
  234. MethodInfo minfo = (MethodInfo)list.get(i);
  235. String desc = minfo.getDescriptor();
  236. minfo.setDescriptor(Descriptor.rename(desc, classnames));
  237. }
  238. list = fields;
  239. n = list.size();
  240. for (int i = 0; i < n; ++i) {
  241. FieldInfo finfo = (FieldInfo)list.get(i);
  242. String desc = finfo.getDescriptor();
  243. finfo.setDescriptor(Descriptor.rename(desc, classnames));
  244. }
  245. }
  246. /**
  247. * Returns the names of the interfaces implemented by the class.
  248. */
  249. public String[] getInterfaces() {
  250. if (interfaces == null)
  251. return new String[0];
  252. else {
  253. int n = interfaces.length;
  254. String[] list = new String[n];
  255. for (int i = 0; i < n; ++i)
  256. list[i] = constPool.getClassInfo(interfaces[i]);
  257. return list;
  258. }
  259. }
  260. /**
  261. * Sets the interfaces.
  262. *
  263. * @param nameList the names of the interfaces.
  264. */
  265. public void setInterfaces(String[] nameList) {
  266. if (nameList != null) {
  267. int n = nameList.length;
  268. interfaces = new int[n];
  269. for (int i = 0; i < n; ++i)
  270. interfaces[i] = constPool.addClassInfo(nameList[i]);
  271. }
  272. }
  273. /**
  274. * Appends an interface to the
  275. * interfaces implemented by the class.
  276. */
  277. public void addInterface(String name) {
  278. int info = constPool.addClassInfo(name);
  279. if (interfaces == null) {
  280. interfaces = new int[1];
  281. interfaces[0] = info;
  282. }
  283. else {
  284. int n = interfaces.length;
  285. int[] newarray = new int[n + 1];
  286. System.arraycopy(interfaces, 0, newarray, 0, n);
  287. newarray[n] = info;
  288. interfaces = newarray;
  289. }
  290. }
  291. /**
  292. * Returns all the fields declared in the class.
  293. *
  294. * @return a list of <code>FieldInfo</code>.
  295. * @see FieldInfo
  296. */
  297. public List getFields() {
  298. return fields;
  299. }
  300. /**
  301. * Appends a field to the class.
  302. */
  303. public void addField(FieldInfo finfo) throws CannotCompileException {
  304. testExistingField(finfo.getName(), finfo.getDescriptor());
  305. fields.add(finfo);
  306. }
  307. private void addField0(FieldInfo finfo) {
  308. fields.add(finfo);
  309. }
  310. private void testExistingField(String name, String descriptor)
  311. throws CannotCompileException
  312. {
  313. ListIterator it = fields.listIterator(0);
  314. while (it.hasNext()) {
  315. FieldInfo minfo = (FieldInfo)it.next();
  316. if (minfo.getName().equals(name))
  317. throw new CannotCompileException("duplicate field: " + name);
  318. }
  319. }
  320. /**
  321. * Returns all the methods declared in the class.
  322. *
  323. * @return a list of <code>MethodInfo</code>.
  324. * @see MethodInfo
  325. */
  326. public List getMethods() {
  327. return methods;
  328. }
  329. /**
  330. * Returns the method with the specified name. If there are multiple
  331. * methods with that name, this method returns one of them.
  332. *
  333. * @return null if no such a method is found.
  334. */
  335. public MethodInfo getMethod(String name) {
  336. LinkedList list = methods;
  337. int n = list.size();
  338. for (int i = 0; i < n; ++i) {
  339. MethodInfo minfo = (MethodInfo)list.get(i);
  340. if (minfo.getName().equals(name))
  341. return minfo;
  342. }
  343. return null;
  344. }
  345. /**
  346. * Returns a static initializer (class initializer), or null if
  347. * it does not exist.
  348. */
  349. public MethodInfo getStaticInitializer() {
  350. return getMethod(MethodInfo.nameClinit);
  351. }
  352. /**
  353. * Appends a method to the class.
  354. */
  355. public void addMethod(MethodInfo minfo) throws CannotCompileException {
  356. testExistingMethod(minfo.getName(), minfo.getDescriptor());
  357. methods.add(minfo);
  358. }
  359. private void addMethod0(MethodInfo minfo) {
  360. methods.add(minfo);
  361. }
  362. private void testExistingMethod(String name, String descriptor)
  363. throws CannotCompileException
  364. {
  365. ListIterator it = methods.listIterator(0);
  366. while (it.hasNext()) {
  367. MethodInfo minfo = (MethodInfo)it.next();
  368. if (minfo.getName().equals(name)
  369. && Descriptor.eqSignature(minfo.getDescriptor(), descriptor))
  370. throw new CannotCompileException("duplicate method: " + name);
  371. }
  372. }
  373. /**
  374. * Returns all the attributes.
  375. *
  376. * @return a list of <code>AttributeInfo</code> objects.
  377. * @see AttributeInfo
  378. */
  379. public List getAttributes() {
  380. return attributes;
  381. }
  382. /**
  383. * Create an empty (null) attribute "RuntimeInvisibleAnnotations"
  384. * Usually used so that you can start adding annotations to a particular thing
  385. */
  386. public void createRuntimeInvisibleGroup() {
  387. if (runtimeInvisible == null) {
  388. AttributeInfo attr =
  389. new AttributeInfo(constPool, "RuntimeInvisibleAnnotations");
  390. addAttribute(attr);
  391. runtimeInvisible = new AnnotationGroup(attr);
  392. }
  393. }
  394. /**
  395. * Create an empty (null) attribute "RuntimeVisibleAnnotations"
  396. * Usually used so that you can start adding annotations to a particular thing
  397. */
  398. public void createRuntimeVisibleGroup() {
  399. if (runtimeVisible == null) {
  400. AttributeInfo attr =
  401. new AttributeInfo(constPool, "RuntimeVisibleAnnotations");
  402. addAttribute(attr);
  403. runtimeVisible = new AnnotationGroup(attr);
  404. }
  405. }
  406. /**
  407. * Return access object for getting info about annotations
  408. * This returns runtime invisible annotations as pertains to the
  409. * CLASS RetentionPolicy
  410. * @return
  411. */
  412. public AnnotationGroup getRuntimeInvisibleAnnotations() {
  413. if (runtimeInvisible != null)
  414. return runtimeInvisible;
  415. AttributeInfo invisible = getAttribute("RuntimeInvisibleAnnotations");
  416. if (invisible == null)
  417. return null;
  418. runtimeInvisible = new AnnotationGroup(invisible);
  419. return runtimeInvisible;
  420. }
  421. /**
  422. * Return access object for getting info about annotations
  423. * This returns runtime visible annotations as pertains to the
  424. * RUNTIME RetentionPolicy
  425. * @return
  426. */
  427. public AnnotationGroup getRuntimeVisibleAnnotations() {
  428. if (runtimeVisible != null)
  429. return runtimeVisible;
  430. AttributeInfo visible = getAttribute("RuntimeVisibleAnnotations");
  431. if (visible == null)
  432. return null;
  433. runtimeVisible = new AnnotationGroup(visible);
  434. return runtimeVisible;
  435. }
  436. /**
  437. * Returns the attribute with the specified name.
  438. *
  439. * @param name attribute name
  440. */
  441. public AttributeInfo getAttribute(String name) {
  442. LinkedList list = attributes;
  443. int n = list.size();
  444. for (int i = 0; i < n; ++i) {
  445. AttributeInfo ai = (AttributeInfo)list.get(i);
  446. if (ai.getName().equals(name))
  447. return ai;
  448. }
  449. return null;
  450. }
  451. /**
  452. * Appends an attribute. If there is already an attribute with
  453. * the same name, the new one substitutes for it.
  454. */
  455. public void addAttribute(AttributeInfo info) {
  456. AttributeInfo.remove(attributes, info.getName());
  457. attributes.add(info);
  458. }
  459. /**
  460. * Returns the source file containing this class.
  461. *
  462. * @return null if this information is not available.
  463. */
  464. public String getSourceFile() {
  465. SourceFileAttribute sf
  466. = (SourceFileAttribute)getAttribute(SourceFileAttribute.tag);
  467. if (sf == null)
  468. return null;
  469. else
  470. return sf.getFileName();
  471. }
  472. private void read(DataInputStream in) throws IOException {
  473. int i, n;
  474. int magic = in.readInt();
  475. if (magic != 0xCAFEBABE)
  476. throw new IOException("non class file");
  477. int major = in.readUnsignedShort();
  478. int minor = in.readUnsignedShort();
  479. constPool = new ConstPool(in);
  480. accessFlags = in.readUnsignedShort();
  481. thisClass = in.readUnsignedShort();
  482. constPool.setThisClassInfo(thisClass);
  483. superClass = in.readUnsignedShort();
  484. n = in.readUnsignedShort();
  485. if (n == 0)
  486. interfaces = null;
  487. else {
  488. interfaces = new int[n];
  489. for (i = 0; i < n; ++i)
  490. interfaces[i] = in.readUnsignedShort();
  491. }
  492. ConstPool cp = constPool;
  493. n = in.readUnsignedShort();
  494. fields = new LinkedList();
  495. for (i = 0; i < n; ++i)
  496. addField0(new FieldInfo(cp, in));
  497. n = in.readUnsignedShort();
  498. methods = new LinkedList();
  499. for (i = 0; i < n; ++i)
  500. addMethod0(new MethodInfo(cp, in));
  501. attributes = new LinkedList();
  502. n = in.readUnsignedShort();
  503. for (i = 0; i < n; ++i)
  504. addAttribute(AttributeInfo.read(cp, in));
  505. thisclassname = constPool.getClassInfo(thisClass);
  506. }
  507. /**
  508. * Writes a class file represened by this object
  509. * into an output stream.
  510. */
  511. public void write(DataOutputStream out) throws IOException {
  512. int i, n;
  513. out.writeInt(0xCAFEBABE); // magic
  514. out.writeShort(3); // major version
  515. out.writeShort(45); // minor version
  516. constPool.write(out); // constant pool
  517. out.writeShort(accessFlags);
  518. out.writeShort(thisClass);
  519. out.writeShort(superClass);
  520. if (interfaces == null)
  521. n = 0;
  522. else
  523. n = interfaces.length;
  524. out.writeShort(n);
  525. for (i = 0; i < n; ++i)
  526. out.writeShort(interfaces[i]);
  527. LinkedList list = fields;
  528. n = list.size();
  529. out.writeShort(n);
  530. for (i = 0; i < n; ++i) {
  531. FieldInfo finfo = (FieldInfo)list.get(i);
  532. finfo.write(out);
  533. }
  534. list = methods;
  535. n = list.size();
  536. out.writeShort(n);
  537. for (i = 0; i < n; ++i) {
  538. MethodInfo minfo = (MethodInfo)list.get(i);
  539. minfo.write(out);
  540. }
  541. out.writeShort(attributes.size());
  542. AttributeInfo.writeAll(attributes, out);
  543. }
  544. }