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

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