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

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