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.

CtClass.java 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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 java.io.BufferedOutputStream;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.DataOutputStream;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.OutputStream;
  24. import java.net.URL;
  25. import java.security.ProtectionDomain;
  26. import java.util.Collection;
  27. import javassist.bytecode.ClassFile;
  28. import javassist.bytecode.Descriptor;
  29. import javassist.bytecode.Opcode;
  30. import javassist.expr.ExprEditor;
  31. /* Note:
  32. *
  33. * This class is an abstract class and several methods just return null
  34. * or throw an exception. Those methods are overridden in subclasses
  35. * of this class. Read the source code of CtClassType if you are
  36. * interested in the implementation of Javassist.
  37. *
  38. * Subclasses of CtClass are CtClassType, CtPrimitiveType, and CtArray.
  39. */
  40. /**
  41. * An instance of <code>CtClass</code> represents a class.
  42. * It is obtained from <code>ClassPool</code>.
  43. *
  44. * @see ClassPool#get(String)
  45. */
  46. public abstract class CtClass {
  47. protected String qualifiedName;
  48. /**
  49. * If the value of this field is not null, then all class
  50. * files modified by Javassist are saved under the directory
  51. * specified by this variable. For example, if the value is
  52. * <code>"./debug"</code>, then all class files are saved
  53. * there. The directory name must not end with a directory
  54. * separator such as <code>/</code>.
  55. *
  56. * <p>The default value is null.
  57. *
  58. * @see #debugWriteFile(String)
  59. * @since 3.16
  60. */
  61. public static String debugDump = null;
  62. /**
  63. * The version number of this release.
  64. */
  65. public static final String version = "3.20.0-GA";
  66. /**
  67. * Prints the version number and the copyright notice.
  68. *
  69. * <p>The following command invokes this method:
  70. *
  71. * <pre>java -jar javassist.jar</pre>
  72. */
  73. public static void main(String[] args) {
  74. System.out.println("Javassist version " + CtClass.version);
  75. System.out.println("Copyright (C) 1999-2015 Shigeru Chiba."
  76. + " All Rights Reserved.");
  77. }
  78. static final String javaLangObject = "java.lang.Object";
  79. /**
  80. * The <code>CtClass</code> object representing
  81. * the <code>boolean</code> type.
  82. */
  83. public static CtClass booleanType;
  84. /**
  85. * The <code>CtClass</code> object representing
  86. * the <code>char</code> type.
  87. */
  88. public static CtClass charType;
  89. /**
  90. * The <code>CtClass</code> object representing
  91. * the <code>byte</code> type.
  92. */
  93. public static CtClass byteType;
  94. /**
  95. * The <code>CtClass</code> object representing
  96. * the <code>short</code> type.
  97. */
  98. public static CtClass shortType;
  99. /**
  100. * The <code>CtClass</code> object representing
  101. * the <code>int</code> type.
  102. */
  103. public static CtClass intType;
  104. /**
  105. * The <code>CtClass</code> object representing
  106. * the <code>long</code> type.
  107. */
  108. public static CtClass longType;
  109. /**
  110. * The <code>CtClass</code> object representing
  111. * the <code>float</code> type.
  112. */
  113. public static CtClass floatType;
  114. /**
  115. * The <code>CtClass</code> object representing
  116. * the <code>double</code> type.
  117. */
  118. public static CtClass doubleType;
  119. /**
  120. * The <code>CtClass</code> object representing
  121. * the <code>void</code> type.
  122. */
  123. public static CtClass voidType;
  124. static CtClass[] primitiveTypes;
  125. static {
  126. primitiveTypes = new CtClass[9];
  127. booleanType =
  128. new CtPrimitiveType("boolean", 'Z', "java.lang.Boolean",
  129. "booleanValue", "()Z", Opcode.IRETURN,
  130. Opcode.T_BOOLEAN, 1);
  131. primitiveTypes[0] = booleanType;
  132. charType = new CtPrimitiveType("char", 'C', "java.lang.Character",
  133. "charValue", "()C", Opcode.IRETURN,
  134. Opcode.T_CHAR, 1);
  135. primitiveTypes[1] = charType;
  136. byteType = new CtPrimitiveType("byte", 'B', "java.lang.Byte",
  137. "byteValue", "()B", Opcode.IRETURN,
  138. Opcode.T_BYTE, 1);
  139. primitiveTypes[2] = byteType;
  140. shortType = new CtPrimitiveType("short", 'S', "java.lang.Short",
  141. "shortValue", "()S", Opcode.IRETURN,
  142. Opcode.T_SHORT, 1);
  143. primitiveTypes[3] = shortType;
  144. intType = new CtPrimitiveType("int", 'I', "java.lang.Integer",
  145. "intValue", "()I", Opcode.IRETURN,
  146. Opcode.T_INT, 1);
  147. primitiveTypes[4] = intType;
  148. longType = new CtPrimitiveType("long", 'J', "java.lang.Long",
  149. "longValue", "()J", Opcode.LRETURN,
  150. Opcode.T_LONG, 2);
  151. primitiveTypes[5] = longType;
  152. floatType = new CtPrimitiveType("float", 'F', "java.lang.Float",
  153. "floatValue", "()F", Opcode.FRETURN,
  154. Opcode.T_FLOAT, 1);
  155. primitiveTypes[6] = floatType;
  156. doubleType = new CtPrimitiveType("double", 'D', "java.lang.Double",
  157. "doubleValue", "()D", Opcode.DRETURN,
  158. Opcode.T_DOUBLE, 2);
  159. primitiveTypes[7] = doubleType;
  160. voidType = new CtPrimitiveType("void", 'V', "java.lang.Void",
  161. null, null, Opcode.RETURN, 0, 0);
  162. primitiveTypes[8] = voidType;
  163. }
  164. protected CtClass(String name) {
  165. qualifiedName = name;
  166. }
  167. /**
  168. * Converts the object to a string.
  169. */
  170. public String toString() {
  171. StringBuffer buf = new StringBuffer(getClass().getName());
  172. buf.append("@");
  173. buf.append(Integer.toHexString(hashCode()));
  174. buf.append("[");
  175. extendToString(buf);
  176. buf.append("]");
  177. return buf.toString();
  178. }
  179. /**
  180. * Implemented in subclasses to add to the {@link #toString()} result.
  181. * Subclasses should put a space before each token added to the buffer.
  182. */
  183. protected void extendToString(StringBuffer buffer) {
  184. buffer.append(getName());
  185. }
  186. /**
  187. * Returns a <code>ClassPool</code> for this class.
  188. */
  189. public ClassPool getClassPool() { return null; }
  190. /**
  191. * Returns a class file for this class.
  192. *
  193. * <p>This method is not available if <code>isFrozen()</code>
  194. * is true.
  195. */
  196. public ClassFile getClassFile() {
  197. checkModify();
  198. return getClassFile2();
  199. }
  200. /**
  201. * Returns a class file for this class (read only).
  202. * Normal applications do not need calling this method. Use
  203. * <code>getClassFile()</code>.
  204. *
  205. * <p>The <code>ClassFile</code> object obtained by this method
  206. * is read only. Changes to this object might not be reflected
  207. * on a class file generated by <code>toBytecode()</code>,
  208. * <code>toClass()</code>, etc.
  209. *
  210. * <p>This method is available even if <code>isFrozen()</code>
  211. * is true. However, if the class is frozen, it might be also
  212. * pruned.
  213. *
  214. * @see CtClass#getClassFile()
  215. * @see CtClass#isFrozen()
  216. * @see CtClass#prune()
  217. */
  218. public ClassFile getClassFile2() { return null; }
  219. /**
  220. * Undocumented method. Do not use; internal-use only.
  221. */
  222. public javassist.compiler.AccessorMaker getAccessorMaker() {
  223. return null;
  224. }
  225. /**
  226. * Returns the uniform resource locator (URL) of the class file.
  227. */
  228. public URL getURL() throws NotFoundException {
  229. throw new NotFoundException(getName());
  230. }
  231. /**
  232. * Returns true if the definition of the class has been modified.
  233. */
  234. public boolean isModified() { return false; }
  235. /**
  236. * Returns true if the class has been loaded or written out
  237. * and thus it cannot be modified any more.
  238. *
  239. * @see #defrost()
  240. * @see #detach()
  241. */
  242. public boolean isFrozen() { return true; }
  243. /**
  244. * Makes the class frozen.
  245. *
  246. * @see #isFrozen()
  247. * @see #defrost()
  248. * @since 3.6
  249. */
  250. public void freeze() {}
  251. /* Note: this method is overridden by CtClassType
  252. */
  253. void checkModify() throws RuntimeException {
  254. if (isFrozen())
  255. throw new RuntimeException(getName() + " class is frozen");
  256. // isModified() must return true after this method is invoked.
  257. }
  258. /**
  259. * Defrosts the class so that the class can be modified again.
  260. *
  261. * <p>To avoid changes that will be never reflected,
  262. * the class is frozen to be unmodifiable if it is loaded or
  263. * written out. This method should be called only in a case
  264. * that the class will be reloaded or written out later again.
  265. *
  266. * <p>If <code>defrost()</code> will be called later, pruning
  267. * must be disallowed in advance.
  268. *
  269. * @see #isFrozen()
  270. * @see #stopPruning(boolean)
  271. * @see #detach()
  272. */
  273. public void defrost() {
  274. throw new RuntimeException("cannot defrost " + getName());
  275. }
  276. /**
  277. * Returns <code>true</code> if this object represents a primitive
  278. * Java type: boolean, byte, char, short, int, long, float, double,
  279. * or void.
  280. */
  281. public boolean isPrimitive() { return false; }
  282. /**
  283. * Returns <code>true</code> if this object represents an array type.
  284. */
  285. public boolean isArray() {
  286. return false;
  287. }
  288. /**
  289. * If this object represents an array, this method returns the component
  290. * type of the array. Otherwise, it returns <code>null</code>.
  291. */
  292. public CtClass getComponentType() throws NotFoundException {
  293. return null;
  294. }
  295. /**
  296. * Returns <code>true</code> if this class extends or implements
  297. * <code>clazz</code>. It also returns <code>true</code> if
  298. * this class is the same as <code>clazz</code>.
  299. */
  300. public boolean subtypeOf(CtClass clazz) throws NotFoundException {
  301. return this == clazz || getName().equals(clazz.getName());
  302. }
  303. /**
  304. * Obtains the fully-qualified name of the class.
  305. */
  306. public String getName() { return qualifiedName; }
  307. /**
  308. * Obtains the not-qualified class name.
  309. */
  310. public final String getSimpleName() {
  311. String qname = qualifiedName;
  312. int index = qname.lastIndexOf('.');
  313. if (index < 0)
  314. return qname;
  315. else
  316. return qname.substring(index + 1);
  317. }
  318. /**
  319. * Obtains the package name. It may be <code>null</code>.
  320. */
  321. public final String getPackageName() {
  322. String qname = qualifiedName;
  323. int index = qname.lastIndexOf('.');
  324. if (index < 0)
  325. return null;
  326. else
  327. return qname.substring(0, index);
  328. }
  329. /**
  330. * Sets the class name
  331. *
  332. * @param name fully-qualified name
  333. */
  334. public void setName(String name) {
  335. checkModify();
  336. if (name != null)
  337. qualifiedName = name;
  338. }
  339. /**
  340. * Returns the generic signature of the class.
  341. *
  342. * <p>The generics of Java is implemented by the erasure technique.
  343. * After compilation, all type parameters are dropped off from the
  344. * main part of a class file. However, for reflection, the type
  345. * parameters are encoded into generic signatures and attached
  346. * to a class file.
  347. *
  348. * @return null if the generic signature is not included.
  349. * @see javassist.bytecode.SignatureAttribute#toClassSignature(String)
  350. * @see CtMember#getGenericSignature()
  351. * @since 3.17
  352. */
  353. public String getGenericSignature() { return null; }
  354. /**
  355. * Sets the generic signature of the class.
  356. *
  357. * <p>The generics of Java is implemented by the erasure technique.
  358. * After compilation, all type parameters are dropped off from the
  359. * main part of a class file. However, for reflection, the type
  360. * parameters must be encoded into generic signatures and attached
  361. * to a class file.
  362. *
  363. * <p>For example,
  364. *
  365. * <pre>class List&lt;T&gt; {
  366. * T value;
  367. * T get() { return value; }
  368. * void set(T v) { value = v; }
  369. * }
  370. * </pre>
  371. *
  372. * <p>this class is generated by the following code:
  373. *
  374. * <pre>
  375. * ClassPool pool = ClassPool.getDefault();
  376. * CtClass cc = pool.makeClass("List");
  377. * CtClass objectClass = pool.get(CtClass.javaLangObject);
  378. * ClassSignature cs = new ClassSignature(
  379. * new TypeParameter[] { new TypeParameter("T") });
  380. * cc.setGenericSignature(cs.encode()); // &lt;T:Ljava/lang/Object;&gt;Ljava/lang/Object;
  381. *
  382. * CtField f = new CtField(objClass, "value", cc);
  383. * TypeVariable tvar = new TypeVariable("T");
  384. * f.setGenericSignature(tvar.encode()); // TT;
  385. * cc.addField(f);
  386. *
  387. * CtMethod m = CtNewMethod.make("public Object get(){return value;}", cc);
  388. * MethodSignature ms = new MethodSignature(null, null, tvar, null);
  389. * m.setGenericSignature(ms.encode()); // ()TT;
  390. * cc.addMethod(m);
  391. *
  392. * CtMethod m2 = CtNewMethod.make("public void set(Object v){value = v;}", cc);
  393. * MethodSignature ms2 = new MethodSignature(null, new Type[] { tvar },
  394. * new BaseType("void"), null);
  395. * m2.setGenericSignature(ms2.encode()); // (TT;)V;
  396. * cc.addMethod(m2);
  397. *
  398. * cc.writeFile();
  399. * </pre>
  400. *
  401. * <p>The generated class file is equivalent to the following:
  402. *
  403. * <pre>class List {
  404. * Object value;
  405. * Object get() { return value; }
  406. * void set(Object v) { value = v; }
  407. * }</pre>
  408. *
  409. * <p>but it includes generic signatures for the class, the field,
  410. * and the methods so that the type variable <code>T</code> can be
  411. * accessible through reflection.
  412. *
  413. * <p><code>MethodSignature</code> is a utility class. You can directly
  414. * pass the signature string to the <code>setGenericSignature</code> method.
  415. * For the specification of the signatures, see Section 4.7.9.1 <i>Signatures</i>
  416. * of The Java Virtual Machine Specification (Java SE 8).
  417. *
  418. * @param sig a generic signature.
  419. * @see javassist.bytecode.SignatureAttribute.ClassSignature#encode()
  420. * @see javassist.bytecode.SignatureAttribute.MethodSignature#encode()
  421. * @see CtMember#setGenericSignature(String)
  422. * @since 3.17
  423. */
  424. public void setGenericSignature(String sig) { checkModify(); }
  425. /**
  426. * Substitutes <code>newName</code> for all occurrences of a class
  427. * name <code>oldName</code> in the class file.
  428. *
  429. * @param oldName replaced class name
  430. * @param newName substituted class name
  431. */
  432. public void replaceClassName(String oldName, String newName) {
  433. checkModify();
  434. }
  435. /**
  436. * Changes class names appearing in the class file according to the
  437. * given <code>map</code>.
  438. *
  439. * <p>All the class names appearing in the class file are tested
  440. * with <code>map</code> to determine whether each class name is
  441. * replaced or not. Thus this method can be used for collecting
  442. * all the class names in the class file. To do that, first define
  443. * a subclass of <code>ClassMap</code> so that <code>get()</code>
  444. * records all the given parameters. Then, make an instance of
  445. * that subclass as an empty hash-table. Finally, pass that instance
  446. * to this method. After this method finishes, that instance would
  447. * contain all the class names appearing in the class file.
  448. *
  449. * @param map the hashtable associating replaced class names
  450. * with substituted names.
  451. */
  452. public void replaceClassName(ClassMap map) {
  453. checkModify();
  454. }
  455. /**
  456. * Returns a collection of the names of all the classes
  457. * referenced in this class.
  458. * That collection includes the name of this class.
  459. *
  460. * <p>This method may return <code>null</code>.
  461. *
  462. * @return a <code>Collection&lt;String&gt;</code> object.
  463. */
  464. public synchronized Collection getRefClasses() {
  465. ClassFile cf = getClassFile2();
  466. if (cf != null) {
  467. ClassMap cm = new ClassMap() {
  468. public void put(String oldname, String newname) {
  469. put0(oldname, newname);
  470. }
  471. public Object get(Object jvmClassName) {
  472. String n = toJavaName((String)jvmClassName);
  473. put0(n, n);
  474. return null;
  475. }
  476. public void fix(String name) {}
  477. };
  478. cf.getRefClasses(cm);
  479. return cm.values();
  480. }
  481. else
  482. return null;
  483. }
  484. /**
  485. * Determines whether this object represents a class or an interface.
  486. * It returns <code>true</code> if this object represents an interface.
  487. */
  488. public boolean isInterface() {
  489. return false;
  490. }
  491. /**
  492. * Determines whether this object represents an annotation type.
  493. * It returns <code>true</code> if this object represents an annotation type.
  494. *
  495. * @since 3.2
  496. */
  497. public boolean isAnnotation() {
  498. return false;
  499. }
  500. /**
  501. * Determines whether this object represents an enum.
  502. * It returns <code>true</code> if this object represents an enum.
  503. *
  504. * @since 3.2
  505. */
  506. public boolean isEnum() {
  507. return false;
  508. }
  509. /**
  510. * Returns the modifiers for this class, encoded in an integer.
  511. * For decoding, use <code>javassist.Modifier</code>.
  512. *
  513. * <p>If the class is a static nested class (a.k.a. static inner class),
  514. * the returned modifiers include <code>Modifier.STATIC</code>.
  515. *
  516. * @see Modifier
  517. */
  518. public int getModifiers() {
  519. return 0;
  520. }
  521. /**
  522. * Returns true if the class has the specified annotation class.
  523. *
  524. * @param clz the annotation class.
  525. * @return <code>true</code> if the annotation is found, otherwise <code>false</code>.
  526. * @since 3.11
  527. */
  528. public boolean hasAnnotation(Class clz) {
  529. return false;
  530. }
  531. /**
  532. * Returns the annotation if the class has the specified annotation class.
  533. * For example, if an annotation <code>@Author</code> is associated
  534. * with this class, an <code>Author</code> object is returned.
  535. * The member values can be obtained by calling methods on
  536. * the <code>Author</code> object.
  537. *
  538. * @param clz the annotation class.
  539. * @return the annotation if found, otherwise <code>null</code>.
  540. * @since 3.11
  541. */
  542. public Object getAnnotation(Class clz) throws ClassNotFoundException {
  543. return null;
  544. }
  545. /**
  546. * Returns the annotations associated with this class.
  547. * For example, if an annotation <code>@Author</code> is associated
  548. * with this class, the returned array contains an <code>Author</code>
  549. * object. The member values can be obtained by calling methods on
  550. * the <code>Author</code> object.
  551. *
  552. * @return an array of annotation-type objects.
  553. * @see CtMember#getAnnotations()
  554. * @since 3.1
  555. */
  556. public Object[] getAnnotations() throws ClassNotFoundException {
  557. return new Object[0];
  558. }
  559. /**
  560. * Returns the annotations associated with this class.
  561. * This method is equivalent to <code>getAnnotations()</code>
  562. * except that, if any annotations are not on the classpath,
  563. * they are not included in the returned array.
  564. *
  565. * @return an array of annotation-type objects.
  566. * @see #getAnnotations()
  567. * @see CtMember#getAvailableAnnotations()
  568. * @since 3.3
  569. */
  570. public Object[] getAvailableAnnotations(){
  571. return new Object[0];
  572. }
  573. /**
  574. * Returns an array of nested classes declared in the class.
  575. * Nested classes are inner classes, anonymous classes, local classes,
  576. * and static nested classes. This simply calls <code>getNestedClasses()</code>.
  577. *
  578. * @see #getNestedClasses()
  579. * @since 3.15
  580. */
  581. public CtClass[] getDeclaredClasses() throws NotFoundException {
  582. return getNestedClasses();
  583. }
  584. /**
  585. * Returns an array of nested classes declared in the class.
  586. * Nested classes are inner classes, anonymous classes, local classes,
  587. * and static nested classes.
  588. *
  589. * @since 3.2
  590. */
  591. public CtClass[] getNestedClasses() throws NotFoundException {
  592. return new CtClass[0];
  593. }
  594. /**
  595. * Sets the modifiers.
  596. *
  597. * <p>If the class is a nested class, this method also modifies
  598. * the class declaring that nested class (i.e. the enclosing
  599. * class is modified).
  600. *
  601. * @param mod modifiers encoded by
  602. * <code>javassist.Modifier</code>
  603. * @see Modifier
  604. */
  605. public void setModifiers(int mod) {
  606. checkModify();
  607. }
  608. /**
  609. * Determines whether the class directly or indirectly extends
  610. * the given class. If this class extends a class A and
  611. * the class A extends a class B, then subclassof(B) returns true.
  612. *
  613. * <p>This method returns true if the given class is identical to
  614. * the class represented by this object.
  615. */
  616. public boolean subclassOf(CtClass superclass) {
  617. return false;
  618. }
  619. /**
  620. * Obtains the class object representing the superclass of the
  621. * class.
  622. * It returns null if this object represents the
  623. * <code>java.lang.Object</code> class and thus it does not have
  624. * the super class.
  625. *
  626. * <p>If this object represents an interface, this method
  627. * always returns the <code>java.lang.Object</code> class.
  628. * To obtain the super interfaces
  629. * extended by that interface, call <code>getInterfaces()</code>.
  630. */
  631. public CtClass getSuperclass() throws NotFoundException {
  632. return null;
  633. }
  634. /**
  635. * Changes a super class unless this object represents an interface.
  636. * The new super class must be compatible with the old one; for example,
  637. * it should inherit from the old super class.
  638. *
  639. * <p>If this object represents an interface, this method is equivalent
  640. * to <code>addInterface()</code>; it appends <code>clazz</code> to
  641. * the list of the super interfaces extended by that interface.
  642. * Note that an interface can extend multiple super interfaces.
  643. *
  644. * @see #replaceClassName(String, String)
  645. * @see #replaceClassName(ClassMap)
  646. */
  647. public void setSuperclass(CtClass clazz) throws CannotCompileException {
  648. checkModify();
  649. }
  650. /**
  651. * Obtains the class objects representing the interfaces implemented
  652. * by the class or, if this object represents an interface, the interfaces
  653. * extended by that interface.
  654. */
  655. public CtClass[] getInterfaces() throws NotFoundException {
  656. return new CtClass[0];
  657. }
  658. /**
  659. * Sets implemented interfaces. If this object represents an interface,
  660. * this method sets the interfaces extended by that interface.
  661. *
  662. * @param list a list of the <code>CtClass</code> objects
  663. * representing interfaces, or
  664. * <code>null</code> if the class implements
  665. * no interfaces.
  666. */
  667. public void setInterfaces(CtClass[] list) {
  668. checkModify();
  669. }
  670. /**
  671. * Adds an interface.
  672. *
  673. * @param anInterface the added interface.
  674. */
  675. public void addInterface(CtClass anInterface) {
  676. checkModify();
  677. }
  678. /**
  679. * If this class is a member class or interface of another class,
  680. * then the class enclosing this class is returned.
  681. *
  682. * @return null if this class is a top-level class or an anonymous class.
  683. */
  684. public CtClass getDeclaringClass() throws NotFoundException {
  685. return null;
  686. }
  687. /**
  688. * Returns the immediately enclosing method of this class.
  689. * This method works only with JDK 1.5 or later.
  690. *
  691. * @return null if this class is not a local class or an anonymous
  692. * class.
  693. * @deprecated The enclosing method might be a constructor.
  694. * Use {@link #getEnclosingBehavior()}.
  695. * @see #getEnclosingBehavior()
  696. */
  697. public final CtMethod getEnclosingMethod() throws NotFoundException {
  698. CtBehavior b = getEnclosingBehavior();
  699. if (b == null)
  700. return null;
  701. else if (b instanceof CtMethod)
  702. return (CtMethod)b;
  703. else
  704. throw new NotFoundException(b.getLongName() + " is enclosing " + getName());
  705. }
  706. /**
  707. * Returns the immediately enclosing method of this class.
  708. * It might be not a method but a constructor.
  709. * This method works only with JDK 1.5 or later.
  710. *
  711. * @return null if this class is not a local class or an anonymous
  712. * class.
  713. */
  714. public CtBehavior getEnclosingBehavior() throws NotFoundException {
  715. return null;
  716. }
  717. /**
  718. * Makes a new public nested class. If this method is called,
  719. * the <code>CtClass</code>, which encloses the nested class, is modified
  720. * since a class file includes a list of nested classes.
  721. *
  722. * <p>The current implementation only supports a static nested class.
  723. * <code>isStatic</code> must be true.
  724. *
  725. * @param name the simple name of the nested class.
  726. * @param isStatic true if the nested class is static.
  727. */
  728. public CtClass makeNestedClass(String name, boolean isStatic) {
  729. throw new RuntimeException(getName() + " is not a class");
  730. }
  731. /**
  732. * Returns an array containing <code>CtField</code> objects
  733. * representing all the non-private fields of the class.
  734. * That array includes non-private fields inherited from the
  735. * superclasses.
  736. */
  737. public CtField[] getFields() { return new CtField[0]; }
  738. /**
  739. * Returns the field with the specified name. The returned field
  740. * may be a private field declared in a super class or interface.
  741. */
  742. public CtField getField(String name) throws NotFoundException {
  743. return getField(name, null);
  744. }
  745. /**
  746. * Returns the field with the specified name and type. The returned field
  747. * may be a private field declared in a super class or interface.
  748. * Unlike Java, the JVM allows a class to have
  749. * multiple fields with the same name but different types.
  750. *
  751. * @param name the field name.
  752. * @param desc the type descriptor of the field. It is available by
  753. * {@link CtField#getSignature()}.
  754. * @see CtField#getSignature()
  755. */
  756. public CtField getField(String name, String desc) throws NotFoundException {
  757. throw new NotFoundException(name);
  758. }
  759. /**
  760. * @return null if the specified field is not found.
  761. */
  762. CtField getField2(String name, String desc) { return null; }
  763. /**
  764. * Gets all the fields declared in the class. The inherited fields
  765. * are not included.
  766. *
  767. * <p>Note: the result does not include inherited fields.
  768. */
  769. public CtField[] getDeclaredFields() { return new CtField[0]; }
  770. /**
  771. * Retrieves the field with the specified name among the fields
  772. * declared in the class.
  773. *
  774. * <p>Note: this method does not search the super classes.
  775. */
  776. public CtField getDeclaredField(String name) throws NotFoundException {
  777. throw new NotFoundException(name);
  778. }
  779. /**
  780. * Retrieves the field with the specified name and type among the fields
  781. * declared in the class. Unlike Java, the JVM allows a class to have
  782. * multiple fields with the same name but different types.
  783. *
  784. * <p>Note: this method does not search the super classes.
  785. *
  786. * @param name the field name.
  787. * @param desc the type descriptor of the field. It is available by
  788. * {@link CtField#getSignature()}.
  789. * @see CtField#getSignature()
  790. */
  791. public CtField getDeclaredField(String name, String desc) throws NotFoundException {
  792. throw new NotFoundException(name);
  793. }
  794. /**
  795. * Gets all the constructors and methods declared in the class.
  796. */
  797. public CtBehavior[] getDeclaredBehaviors() {
  798. return new CtBehavior[0];
  799. }
  800. /**
  801. * Returns an array containing <code>CtConstructor</code> objects
  802. * representing all the non-private constructors of the class.
  803. */
  804. public CtConstructor[] getConstructors() {
  805. return new CtConstructor[0];
  806. }
  807. /**
  808. * Returns the constructor with the given signature,
  809. * which is represented by a character string
  810. * called method descriptor.
  811. * For details of the method descriptor, see the JVM specification
  812. * or <code>javassist.bytecode.Descriptor</code>.
  813. *
  814. * @param desc method descriptor
  815. * @see javassist.bytecode.Descriptor
  816. */
  817. public CtConstructor getConstructor(String desc)
  818. throws NotFoundException
  819. {
  820. throw new NotFoundException("no such constructor");
  821. }
  822. /**
  823. * Gets all the constructors declared in the class.
  824. *
  825. * @see javassist.CtConstructor
  826. */
  827. public CtConstructor[] getDeclaredConstructors() {
  828. return new CtConstructor[0];
  829. }
  830. /**
  831. * Returns a constructor receiving the specified parameters.
  832. *
  833. * @param params parameter types.
  834. */
  835. public CtConstructor getDeclaredConstructor(CtClass[] params)
  836. throws NotFoundException
  837. {
  838. String desc = Descriptor.ofConstructor(params);
  839. return getConstructor(desc);
  840. }
  841. /**
  842. * Gets the class initializer (static constructor)
  843. * declared in the class.
  844. * This method returns <code>null</code> if
  845. * no class initializer is not declared.
  846. *
  847. * @see #makeClassInitializer()
  848. * @see javassist.CtConstructor
  849. */
  850. public CtConstructor getClassInitializer() {
  851. return null;
  852. }
  853. /**
  854. * Returns an array containing <code>CtMethod</code> objects
  855. * representing all the non-private methods of the class.
  856. * That array includes non-private methods inherited from the
  857. * superclasses.
  858. */
  859. public CtMethod[] getMethods() {
  860. return new CtMethod[0];
  861. }
  862. /**
  863. * Returns the method with the given name and signature.
  864. * The returned method may be declared in a super class.
  865. * The method signature is represented by a character string
  866. * called method descriptor,
  867. * which is defined in the JVM specification.
  868. *
  869. * @param name method name
  870. * @param desc method descriptor
  871. * @see CtBehavior#getSignature()
  872. * @see javassist.bytecode.Descriptor
  873. */
  874. public CtMethod getMethod(String name, String desc)
  875. throws NotFoundException
  876. {
  877. throw new NotFoundException(name);
  878. }
  879. /**
  880. * Gets all methods declared in the class. The inherited methods
  881. * are not included.
  882. *
  883. * @see javassist.CtMethod
  884. */
  885. public CtMethod[] getDeclaredMethods() {
  886. return new CtMethod[0];
  887. }
  888. /**
  889. * Retrieves the method with the specified name and parameter types
  890. * among the methods declared in the class.
  891. *
  892. * <p>Note: this method does not search the superclasses.
  893. *
  894. * @param name method name
  895. * @param params parameter types
  896. * @see javassist.CtMethod
  897. */
  898. public CtMethod getDeclaredMethod(String name, CtClass[] params)
  899. throws NotFoundException
  900. {
  901. throw new NotFoundException(name);
  902. }
  903. /**
  904. * Retrieves methods with the specified name among the methods
  905. * declared in the class. Multiple methods with different parameters
  906. * may be returned.
  907. *
  908. * <p>Note: this method does not search the superclasses.</p>
  909. *
  910. * @param name method name.
  911. * @since 3.19
  912. */
  913. public CtMethod[] getDeclaredMethods(String name) throws NotFoundException {
  914. throw new NotFoundException(name);
  915. }
  916. /**
  917. * Retrieves the method with the specified name among the methods
  918. * declared in the class. If there are multiple methods with
  919. * the specified name, then this method returns one of them.
  920. *
  921. * <p>Note: this method does not search the superclasses.
  922. *
  923. * @see javassist.CtMethod
  924. */
  925. public CtMethod getDeclaredMethod(String name) throws NotFoundException {
  926. throw new NotFoundException(name);
  927. }
  928. /**
  929. * Makes an empty class initializer (static constructor).
  930. * If the class already includes a class initializer,
  931. * this method returns it.
  932. *
  933. * @see #getClassInitializer()
  934. */
  935. public CtConstructor makeClassInitializer()
  936. throws CannotCompileException
  937. {
  938. throw new CannotCompileException("not a class");
  939. }
  940. /**
  941. * Adds a constructor. To add a class initializer (static constructor),
  942. * call <code>makeClassInitializer()</code>.
  943. *
  944. * @see #makeClassInitializer()
  945. */
  946. public void addConstructor(CtConstructor c)
  947. throws CannotCompileException
  948. {
  949. checkModify();
  950. }
  951. /**
  952. * Removes a constructor declared in this class.
  953. *
  954. * @param c removed constructor.
  955. * @throws NotFoundException if the constructor is not found.
  956. */
  957. public void removeConstructor(CtConstructor c) throws NotFoundException {
  958. checkModify();
  959. }
  960. /**
  961. * Adds a method.
  962. */
  963. public void addMethod(CtMethod m) throws CannotCompileException {
  964. checkModify();
  965. }
  966. /**
  967. * Removes a method declared in this class.
  968. *
  969. * @param m removed method.
  970. * @throws NotFoundException if the method is not found.
  971. */
  972. public void removeMethod(CtMethod m) throws NotFoundException {
  973. checkModify();
  974. }
  975. /**
  976. * Adds a field.
  977. *
  978. * <p>The <code>CtField</code> belonging to another
  979. * <code>CtClass</code> cannot be directly added to this class.
  980. * Only a field created for this class can be added.
  981. *
  982. * @see javassist.CtField#CtField(CtField,CtClass)
  983. */
  984. public void addField(CtField f) throws CannotCompileException {
  985. addField(f, (CtField.Initializer)null);
  986. }
  987. /**
  988. * Adds a field with an initial value.
  989. *
  990. * <p>The <code>CtField</code> belonging to another
  991. * <code>CtClass</code> cannot be directly added to this class.
  992. * Only a field created for this class can be added.
  993. *
  994. * <p>The initial value is given as an expression written in Java.
  995. * Any regular Java expression can be used for specifying the initial
  996. * value. The followings are examples.
  997. *
  998. * <pre>
  999. * cc.addField(f, "0") // the initial value is 0.
  1000. * cc.addField(f, "i + 1") // i + 1.
  1001. * cc.addField(f, "new Point()"); // a Point object.
  1002. * </pre>
  1003. *
  1004. * <p>Here, the type of variable <code>cc</code> is <code>CtClass</code>.
  1005. * The type of <code>f</code> is <code>CtField</code>.
  1006. *
  1007. * <p>Note: do not change the modifier of the field
  1008. * (in particular, do not add or remove <code>static</code>
  1009. * to/from the modifier)
  1010. * after it is added to the class by <code>addField()</code>.
  1011. *
  1012. * @param init an expression for the initial value.
  1013. *
  1014. * @see javassist.CtField.Initializer#byExpr(String)
  1015. * @see javassist.CtField#CtField(CtField,CtClass)
  1016. */
  1017. public void addField(CtField f, String init)
  1018. throws CannotCompileException
  1019. {
  1020. checkModify();
  1021. }
  1022. /**
  1023. * Adds a field with an initial value.
  1024. *
  1025. * <p>The <code>CtField</code> belonging to another
  1026. * <code>CtClass</code> cannot be directly added to this class.
  1027. * Only a field created for this class can be added.
  1028. *
  1029. * <p>For example,
  1030. *
  1031. * <pre>
  1032. * CtClass cc = ...;
  1033. * addField(new CtField(CtClass.intType, "i", cc),
  1034. * CtField.Initializer.constant(1));
  1035. * </pre>
  1036. *
  1037. * <p>This code adds an <code>int</code> field named "i". The
  1038. * initial value of this field is 1.
  1039. *
  1040. * @param init specifies the initial value of the field.
  1041. *
  1042. * @see javassist.CtField#CtField(CtField,CtClass)
  1043. */
  1044. public void addField(CtField f, CtField.Initializer init)
  1045. throws CannotCompileException
  1046. {
  1047. checkModify();
  1048. }
  1049. /**
  1050. * Removes a field declared in this class.
  1051. *
  1052. * @param f removed field.
  1053. * @throws NotFoundException if the field is not found.
  1054. */
  1055. public void removeField(CtField f) throws NotFoundException {
  1056. checkModify();
  1057. }
  1058. /**
  1059. * Obtains an attribute with the given name.
  1060. * If that attribute is not found in the class file, this
  1061. * method returns null.
  1062. *
  1063. * <p>This is a convenient method mainly for obtaining
  1064. * a user-defined attribute. For dealing with attributes, see the
  1065. * <code>javassist.bytecode</code> package. For example, the following
  1066. * expression returns all the attributes of a class file.
  1067. *
  1068. * <pre>
  1069. * getClassFile().getAttributes()
  1070. * </pre>
  1071. *
  1072. * @param name attribute name
  1073. * @see javassist.bytecode.AttributeInfo
  1074. */
  1075. public byte[] getAttribute(String name) {
  1076. return null;
  1077. }
  1078. /**
  1079. * Adds a named attribute.
  1080. * An arbitrary data (smaller than 64Kb) can be saved in the class
  1081. * file. Some attribute name are reserved by the JVM.
  1082. * The attributes with the non-reserved names are ignored when a
  1083. * class file is loaded into the JVM.
  1084. * If there is already an attribute with
  1085. * the same name, this method substitutes the new one for it.
  1086. *
  1087. * <p>This is a convenient method mainly for adding
  1088. * a user-defined attribute. For dealing with attributes, see the
  1089. * <code>javassist.bytecode</code> package. For example, the following
  1090. * expression adds an attribute <code>info</code> to a class file.
  1091. *
  1092. * <pre>
  1093. * getClassFile().addAttribute(info)
  1094. * </pre>
  1095. *
  1096. * @param name attribute name
  1097. * @param data attribute value
  1098. * @see javassist.bytecode.AttributeInfo
  1099. */
  1100. public void setAttribute(String name, byte[] data) {
  1101. checkModify();
  1102. }
  1103. /**
  1104. * Applies the given converter to all methods and constructors
  1105. * declared in the class. This method calls <code>instrument()</code>
  1106. * on every <code>CtMethod</code> and <code>CtConstructor</code> object
  1107. * in the class.
  1108. *
  1109. * @param converter specifies how to modify.
  1110. */
  1111. public void instrument(CodeConverter converter)
  1112. throws CannotCompileException
  1113. {
  1114. checkModify();
  1115. }
  1116. /**
  1117. * Modifies the bodies of all methods and constructors
  1118. * declared in the class. This method calls <code>instrument()</code>
  1119. * on every <code>CtMethod</code> and <code>CtConstructor</code> object
  1120. * in the class.
  1121. *
  1122. * @param editor specifies how to modify.
  1123. */
  1124. public void instrument(ExprEditor editor)
  1125. throws CannotCompileException
  1126. {
  1127. checkModify();
  1128. }
  1129. /**
  1130. * Converts this class to a <code>java.lang.Class</code> object.
  1131. * Once this method is called, further modifications are not
  1132. * allowed any more.
  1133. * To load the class, this method uses the context class loader
  1134. * of the current thread. If the program is running on some application
  1135. * server, the context class loader might be inappropriate to load the
  1136. * class.
  1137. *
  1138. * <p>This method is provided for convenience. If you need more
  1139. * complex functionality, you should write your own class loader.
  1140. *
  1141. * <p>Note: this method calls <code>toClass()</code>
  1142. * in <code>ClassPool</code>.
  1143. *
  1144. * <p><b>Warining:</b> A Class object returned by this method may not
  1145. * work with a security manager or a signed jar file because a
  1146. * protection domain is not specified.
  1147. *
  1148. * @see #toClass(java.lang.ClassLoader,ProtectionDomain)
  1149. * @see ClassPool#toClass(CtClass)
  1150. */
  1151. public Class toClass() throws CannotCompileException {
  1152. return getClassPool().toClass(this);
  1153. }
  1154. /**
  1155. * Converts this class to a <code>java.lang.Class</code> object.
  1156. * Once this method is called, further modifications are not allowed
  1157. * any more.
  1158. *
  1159. * <p>The class file represented by this <code>CtClass</code> is
  1160. * loaded by the given class loader to construct a
  1161. * <code>java.lang.Class</code> object. Since a private method
  1162. * on the class loader is invoked through the reflection API,
  1163. * the caller must have permissions to do that.
  1164. *
  1165. * <p>An easy way to obtain <code>ProtectionDomain</code> object is
  1166. * to call <code>getProtectionDomain()</code>
  1167. * in <code>java.lang.Class</code>. It returns the domain that
  1168. * the class belongs to.
  1169. *
  1170. * <p>This method is provided for convenience. If you need more
  1171. * complex functionality, you should write your own class loader.
  1172. *
  1173. * <p>Note: this method calls <code>toClass()</code>
  1174. * in <code>ClassPool</code>.
  1175. *
  1176. * @param loader the class loader used to load this class.
  1177. * If it is null, the class loader returned by
  1178. * {@link ClassPool#getClassLoader()} is used.
  1179. * @param domain the protection domain that the class belongs to.
  1180. * If it is null, the default domain created
  1181. * by <code>java.lang.ClassLoader</code> is used.
  1182. * @see ClassPool#toClass(CtClass,java.lang.ClassLoader)
  1183. * @since 3.3
  1184. */
  1185. public Class toClass(ClassLoader loader, ProtectionDomain domain)
  1186. throws CannotCompileException
  1187. {
  1188. ClassPool cp = getClassPool();
  1189. if (loader == null)
  1190. loader = cp.getClassLoader();
  1191. return cp.toClass(this, loader, domain);
  1192. }
  1193. /**
  1194. * Converts this class to a <code>java.lang.Class</code> object.
  1195. *
  1196. * <p><b>Warining:</b> A Class object returned by this method may not
  1197. * work with a security manager or a signed jar file because a
  1198. * protection domain is not specified.
  1199. *
  1200. * @deprecated Replaced by {@link #toClass(ClassLoader,ProtectionDomain)}
  1201. */
  1202. public final Class toClass(ClassLoader loader)
  1203. throws CannotCompileException
  1204. {
  1205. return getClassPool().toClass(this, loader);
  1206. }
  1207. /**
  1208. * Removes this <code>CtClass</code> object from the
  1209. * <code>ClassPool</code>.
  1210. * After this method is called, any method cannot be called on the
  1211. * removed <code>CtClass</code> object.
  1212. *
  1213. * <p>If <code>get()</code> in <code>ClassPool</code> is called
  1214. * with the name of the removed method,
  1215. * the <code>ClassPool</code> will read the class file again
  1216. * and constructs another <code>CtClass</code> object representing
  1217. * the same class.
  1218. */
  1219. public void detach() {
  1220. ClassPool cp = getClassPool();
  1221. CtClass obj = cp.removeCached(getName());
  1222. if (obj != this)
  1223. cp.cacheCtClass(getName(), obj, false);
  1224. }
  1225. /**
  1226. * Disallows (or allows) automatically pruning this <code>CtClass</code>
  1227. * object.
  1228. *
  1229. * <p>
  1230. * Javassist can automatically prune a <code>CtClass</code> object
  1231. * when <code>toBytecode()</code> (or <code>toClass()</code>,
  1232. * <code>writeFile()</code>) is called.
  1233. * Since a <code>ClassPool</code> holds all instances of <code>CtClass</code>
  1234. * even after <code>toBytecode()</code> (or <code>toClass()</code>,
  1235. * <code>writeFile()</code>) is called, pruning may significantly
  1236. * save memory consumption.
  1237. *
  1238. * <p>If <code>ClassPool.doPruning</code> is true, the automatic pruning
  1239. * is on by default. Otherwise, it is off. The default value of
  1240. * <code>ClassPool.doPruning</code> is false.
  1241. *
  1242. * @param stop disallow pruning if true. Otherwise, allow.
  1243. * @return the previous status of pruning. true if pruning is already stopped.
  1244. *
  1245. * @see #detach()
  1246. * @see #prune()
  1247. * @see ClassPool#doPruning
  1248. */
  1249. public boolean stopPruning(boolean stop) { return true; }
  1250. /**
  1251. * Discards unnecessary attributes, in particular,
  1252. * <code>CodeAttribute</code>s (method bodies) of the class,
  1253. * to minimize the memory footprint.
  1254. * After calling this method, the class is read only.
  1255. * It cannot be modified any more.
  1256. * Furthermore, <code>toBytecode()</code>,
  1257. * <code>writeFile()</code>, <code>toClass()</code>,
  1258. * or <code>instrument()</code> cannot be called.
  1259. * However, the method names and signatures in the class etc.
  1260. * are still accessible.
  1261. *
  1262. * <p><code>toBytecode()</code>, <code>writeFile()</code>, and
  1263. * <code>toClass()</code> internally call this method if
  1264. * automatic pruning is on.
  1265. *
  1266. * <p>According to some experiments, pruning does not really reduce
  1267. * memory consumption. Only about 20%. Since pruning takes time,
  1268. * it might not pay off. So the automatic pruning is off by default.
  1269. *
  1270. * @see #stopPruning(boolean)
  1271. * @see #detach()
  1272. * @see ClassPool#doPruning
  1273. *
  1274. * @see #toBytecode()
  1275. * @see #toClass()
  1276. * @see #writeFile()
  1277. * @see #instrument(CodeConverter)
  1278. * @see #instrument(ExprEditor)
  1279. */
  1280. public void prune() {}
  1281. /* Called by get() in ClassPool.
  1282. * CtClassType overrides this method.
  1283. */
  1284. void incGetCounter() {}
  1285. /**
  1286. * If this method is called, the class file will be
  1287. * rebuilt when it is finally generated by
  1288. * <code>toBytecode()</code> and <code>writeFile()</code>.
  1289. * For a performance reason, the symbol table of the
  1290. * class file may contain unused entries, for example,
  1291. * after a method or a filed is deleted.
  1292. * This method
  1293. * removes those unused entries. This removal will
  1294. * minimize the size of the class file.
  1295. *
  1296. * @since 3.8.1
  1297. */
  1298. public void rebuildClassFile() {}
  1299. /**
  1300. * Converts this class to a class file.
  1301. * Once this method is called, further modifications are not
  1302. * possible any more.
  1303. *
  1304. * @return the contents of the class file.
  1305. */
  1306. public byte[] toBytecode() throws IOException, CannotCompileException {
  1307. ByteArrayOutputStream barray = new ByteArrayOutputStream();
  1308. DataOutputStream out = new DataOutputStream(barray);
  1309. try {
  1310. toBytecode(out);
  1311. }
  1312. finally {
  1313. out.close();
  1314. }
  1315. return barray.toByteArray();
  1316. }
  1317. /**
  1318. * Writes a class file represented by this <code>CtClass</code>
  1319. * object in the current directory.
  1320. * Once this method is called, further modifications are not
  1321. * possible any more.
  1322. *
  1323. * @see #debugWriteFile()
  1324. */
  1325. public void writeFile()
  1326. throws NotFoundException, IOException, CannotCompileException
  1327. {
  1328. writeFile(".");
  1329. }
  1330. /**
  1331. * Writes a class file represented by this <code>CtClass</code>
  1332. * object on a local disk.
  1333. * Once this method is called, further modifications are not
  1334. * possible any more.
  1335. *
  1336. * @param directoryName it must end without a directory separator.
  1337. * @see #debugWriteFile(String)
  1338. */
  1339. public void writeFile(String directoryName)
  1340. throws CannotCompileException, IOException
  1341. {
  1342. DataOutputStream out = makeFileOutput(directoryName);
  1343. try {
  1344. toBytecode(out);
  1345. }
  1346. finally {
  1347. out.close();
  1348. }
  1349. }
  1350. protected DataOutputStream makeFileOutput(String directoryName) {
  1351. String classname = getName();
  1352. String filename = directoryName + File.separatorChar
  1353. + classname.replace('.', File.separatorChar) + ".class";
  1354. int pos = filename.lastIndexOf(File.separatorChar);
  1355. if (pos > 0) {
  1356. String dir = filename.substring(0, pos);
  1357. if (!dir.equals("."))
  1358. new File(dir).mkdirs();
  1359. }
  1360. return new DataOutputStream(new BufferedOutputStream(
  1361. new DelayedFileOutputStream(filename)));
  1362. }
  1363. /**
  1364. * Writes a class file as <code>writeFile()</code> does although this
  1365. * method does not prune or freeze the class after writing the class
  1366. * file. Note that, once <code>writeFile()</code> or <code>toBytecode()</code>
  1367. * is called, it cannot be called again since the class is pruned and frozen.
  1368. * This method would be useful for debugging.
  1369. */
  1370. public void debugWriteFile() {
  1371. debugWriteFile(".");
  1372. }
  1373. /**
  1374. * Writes a class file as <code>writeFile()</code> does although this
  1375. * method does not prune or freeze the class after writing the class
  1376. * file. Note that, once <code>writeFile()</code> or <code>toBytecode()</code>
  1377. * is called, it cannot be called again since the class is pruned and frozen.
  1378. * This method would be useful for debugging.
  1379. *
  1380. * @param directoryName it must end without a directory separator.
  1381. */
  1382. public void debugWriteFile(String directoryName) {
  1383. try {
  1384. boolean p = stopPruning(true);
  1385. writeFile(directoryName);
  1386. defrost();
  1387. stopPruning(p);
  1388. }
  1389. catch (Exception e) {
  1390. throw new RuntimeException(e);
  1391. }
  1392. }
  1393. static class DelayedFileOutputStream extends OutputStream {
  1394. private FileOutputStream file;
  1395. private String filename;
  1396. DelayedFileOutputStream(String name) {
  1397. file = null;
  1398. filename = name;
  1399. }
  1400. private void init() throws IOException {
  1401. if (file == null)
  1402. file = new FileOutputStream(filename);
  1403. }
  1404. public void write(int b) throws IOException {
  1405. init();
  1406. file.write(b);
  1407. }
  1408. public void write(byte[] b) throws IOException {
  1409. init();
  1410. file.write(b);
  1411. }
  1412. public void write(byte[] b, int off, int len) throws IOException {
  1413. init();
  1414. file.write(b, off, len);
  1415. }
  1416. public void flush() throws IOException {
  1417. init();
  1418. file.flush();
  1419. }
  1420. public void close() throws IOException {
  1421. init();
  1422. file.close();
  1423. }
  1424. }
  1425. /**
  1426. * Converts this class to a class file.
  1427. * Once this method is called, further modifications are not
  1428. * possible any more.
  1429. *
  1430. * <p>This method dose not close the output stream in the end.
  1431. *
  1432. * @param out the output stream that a class file is written to.
  1433. */
  1434. public void toBytecode(DataOutputStream out)
  1435. throws CannotCompileException, IOException
  1436. {
  1437. throw new CannotCompileException("not a class");
  1438. }
  1439. /**
  1440. * Makes a unique member name. This method guarantees that
  1441. * the returned name is not used as a prefix of any methods
  1442. * or fields visible in this class.
  1443. * If the returned name is XYZ, then any method or field names
  1444. * in this class do not start with XYZ.
  1445. *
  1446. * @param prefix the prefix of the member name.
  1447. */
  1448. public String makeUniqueName(String prefix) {
  1449. throw new RuntimeException("not available in " + getName());
  1450. }
  1451. /* Invoked from ClassPool#compress().
  1452. * This method is overridden by CtClassType.
  1453. */
  1454. void compress() {}
  1455. }