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

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