You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CtClass.java 55KB

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