Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ClassFile.java 18KB

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