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

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