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.

CtNewMethod.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 javassist.CtMethod.ConstParameter;
  18. import javassist.bytecode.AccessFlag;
  19. import javassist.bytecode.Bytecode;
  20. import javassist.bytecode.ConstPool;
  21. import javassist.bytecode.ExceptionsAttribute;
  22. import javassist.bytecode.FieldInfo;
  23. import javassist.bytecode.MethodInfo;
  24. import javassist.compiler.CompileError;
  25. import javassist.compiler.Javac;
  26. /**
  27. * A collection of static methods for creating a <code>CtMethod</code>.
  28. * An instance of this class does not make any sense.
  29. *
  30. * @see CtClass#addMethod(CtMethod)
  31. */
  32. public class CtNewMethod {
  33. /**
  34. * Compiles the given source code and creates a method.
  35. * The source code must include not only the method body
  36. * but the whole declaration, for example,
  37. *
  38. * <pre>"public Object id(Object obj) { return obj; }"</pre>
  39. *
  40. * @param src the source text.
  41. * @param declaring the class to which the created method is added.
  42. */
  43. public static CtMethod make(String src, CtClass declaring)
  44. throws CannotCompileException
  45. {
  46. return make(src, declaring, null, null);
  47. }
  48. /**
  49. * Compiles the given source code and creates a method.
  50. * The source code must include not only the method body
  51. * but the whole declaration, for example,
  52. *
  53. * <pre>"public Object id(Object obj) { return obj; }"</pre>
  54. *
  55. * <p>If the source code includes <code>$proceed()</code>, then
  56. * it is compiled into a method call on the specified object.
  57. *
  58. * @param src the source text.
  59. * @param declaring the class to which the created method is added.
  60. * @param delegateObj the source text specifying the object
  61. * that is called on by <code>$proceed()</code>.
  62. * @param delegateMethod the name of the method
  63. * that is called by <code>$proceed()</code>.
  64. */
  65. public static CtMethod make(String src, CtClass declaring,
  66. String delegateObj, String delegateMethod)
  67. throws CannotCompileException
  68. {
  69. Javac compiler = new Javac(declaring);
  70. try {
  71. if (delegateMethod != null)
  72. compiler.recordProceed(delegateObj, delegateMethod);
  73. CtMember obj = compiler.compile(src);
  74. if (obj instanceof CtMethod)
  75. return (CtMethod)obj;
  76. }
  77. catch (CompileError e) {
  78. throw new CannotCompileException(e);
  79. }
  80. throw new CannotCompileException("not a method");
  81. }
  82. /**
  83. * Creates a public (non-static) method. The created method cannot
  84. * be changed to a static method later.
  85. *
  86. * @param returnType the type of the returned value.
  87. * @param mname the method name.
  88. * @param parameters a list of the parameter types.
  89. * @param exceptions a list of the exception types.
  90. * @param body the source text of the method body.
  91. * It must be a block surrounded by <code>{}</code>.
  92. * If it is <code>null</code>, the created method
  93. * does nothing except returning zero or null.
  94. * @param declaring the class to which the created method is added.
  95. * @see #make(int, CtClass, String, CtClass[], CtClass[], String, CtClass)
  96. */
  97. public static CtMethod make(CtClass returnType,
  98. String mname, CtClass[] parameters,
  99. CtClass[] exceptions,
  100. String body, CtClass declaring)
  101. throws CannotCompileException
  102. {
  103. return make(Modifier.PUBLIC, returnType, mname, parameters, exceptions,
  104. body, declaring);
  105. }
  106. /**
  107. * Creates a method. <code>modifiers</code> can contain
  108. * <code>Modifier.STATIC</code>.
  109. *
  110. * @param modifiers access modifiers.
  111. * @param returnType the type of the returned value.
  112. * @param mname the method name.
  113. * @param parameters a list of the parameter types.
  114. * @param exceptions a list of the exception types.
  115. * @param body the source text of the method body.
  116. * It must be a block surrounded by <code>{}</code>.
  117. * If it is <code>null</code>, the created method
  118. * does nothing except returning zero or null.
  119. * @param declaring the class to which the created method is added.
  120. *
  121. * @see Modifier
  122. */
  123. public static CtMethod make(int modifiers, CtClass returnType,
  124. String mname, CtClass[] parameters,
  125. CtClass[] exceptions,
  126. String body, CtClass declaring)
  127. throws CannotCompileException
  128. {
  129. try {
  130. CtMethod cm
  131. = new CtMethod(returnType, mname, parameters, declaring);
  132. cm.setModifiers(modifiers);
  133. cm.setExceptionTypes(exceptions);
  134. cm.setBody(body);
  135. return cm;
  136. }
  137. catch (NotFoundException e) {
  138. throw new CannotCompileException(e);
  139. }
  140. }
  141. /**
  142. * Creates a copy of a method. This method is provided for creating
  143. * a new method based on an existing method.
  144. * This is a convenience method for calling
  145. * {@link CtMethod#CtMethod(CtMethod, CtClass, ClassMap) this constructor}.
  146. * See the description of the constructor for particular behavior of the copying.
  147. *
  148. * @param src the source method.
  149. * @param declaring the class to which the created method is added.
  150. * @param map the hash table associating original class names
  151. * with substituted names.
  152. * It can be <code>null</code>.
  153. *
  154. * @see CtMethod#CtMethod(CtMethod,CtClass,ClassMap)
  155. */
  156. public static CtMethod copy(CtMethod src, CtClass declaring,
  157. ClassMap map) throws CannotCompileException {
  158. return new CtMethod(src, declaring, map);
  159. }
  160. /**
  161. * Creates a copy of a method with a new name.
  162. * This method is provided for creating
  163. * a new method based on an existing method.
  164. * This is a convenience method for calling
  165. * {@link CtMethod#CtMethod(CtMethod, CtClass, ClassMap) this constructor}.
  166. * See the description of the constructor for particular behavior of the copying.
  167. *
  168. * @param src the source method.
  169. * @param name the name of the created method.
  170. * @param declaring the class to which the created method is added.
  171. * @param map the hash table associating original class names
  172. * with substituted names.
  173. * It can be <code>null</code>.
  174. *
  175. * @see CtMethod#CtMethod(CtMethod,CtClass,ClassMap)
  176. */
  177. public static CtMethod copy(CtMethod src, String name, CtClass declaring,
  178. ClassMap map) throws CannotCompileException {
  179. CtMethod cm = new CtMethod(src, declaring, map);
  180. cm.setName(name);
  181. return cm;
  182. }
  183. /**
  184. * Creates a public abstract method.
  185. *
  186. * @param returnType the type of the returned value
  187. * @param mname the method name
  188. * @param parameters a list of the parameter types
  189. * @param exceptions a list of the exception types
  190. * @param declaring the class to which the created method is added.
  191. *
  192. * @see CtMethod#CtMethod(CtClass,String,CtClass[],CtClass)
  193. */
  194. public static CtMethod abstractMethod(CtClass returnType,
  195. String mname,
  196. CtClass[] parameters,
  197. CtClass[] exceptions,
  198. CtClass declaring)
  199. throws NotFoundException
  200. {
  201. CtMethod cm = new CtMethod(returnType, mname, parameters, declaring);
  202. cm.setExceptionTypes(exceptions);
  203. return cm;
  204. }
  205. /**
  206. * Creates a public getter method. The getter method returns the value
  207. * of the specified field in the class to which this method is added.
  208. * The created method is initially not static even if the field is
  209. * static. Change the modifiers if the method should be static.
  210. *
  211. * @param methodName the name of the getter
  212. * @param field the field accessed.
  213. */
  214. public static CtMethod getter(String methodName, CtField field)
  215. throws CannotCompileException
  216. {
  217. FieldInfo finfo = field.getFieldInfo2();
  218. String fieldType = finfo.getDescriptor();
  219. String desc = "()" + fieldType;
  220. ConstPool cp = finfo.getConstPool();
  221. MethodInfo minfo = new MethodInfo(cp, methodName, desc);
  222. minfo.setAccessFlags(AccessFlag.PUBLIC);
  223. Bytecode code = new Bytecode(cp, 2, 1);
  224. try {
  225. String fieldName = finfo.getName();
  226. if ((finfo.getAccessFlags() & AccessFlag.STATIC) == 0) {
  227. code.addAload(0);
  228. code.addGetfield(Bytecode.THIS, fieldName, fieldType);
  229. }
  230. else
  231. code.addGetstatic(Bytecode.THIS, fieldName, fieldType);
  232. code.addReturn(field.getType());
  233. }
  234. catch (NotFoundException e) {
  235. throw new CannotCompileException(e);
  236. }
  237. minfo.setCodeAttribute(code.toCodeAttribute());
  238. CtClass cc = field.getDeclaringClass();
  239. // a stack map is not needed.
  240. return new CtMethod(minfo, cc);
  241. }
  242. /**
  243. * Creates a public setter method. The setter method assigns the
  244. * value of the first parameter to the specified field
  245. * in the class to which this method is added.
  246. * The created method is not static even if the field is
  247. * static. You may not change it to be static
  248. * by <code>setModifiers()</code> in <code>CtBehavior</code>.
  249. *
  250. * @param methodName the name of the setter
  251. * @param field the field accessed.
  252. */
  253. public static CtMethod setter(String methodName, CtField field)
  254. throws CannotCompileException
  255. {
  256. FieldInfo finfo = field.getFieldInfo2();
  257. String fieldType = finfo.getDescriptor();
  258. String desc = "(" + fieldType + ")V";
  259. ConstPool cp = finfo.getConstPool();
  260. MethodInfo minfo = new MethodInfo(cp, methodName, desc);
  261. minfo.setAccessFlags(AccessFlag.PUBLIC);
  262. Bytecode code = new Bytecode(cp, 3, 3);
  263. try {
  264. String fieldName = finfo.getName();
  265. if ((finfo.getAccessFlags() & AccessFlag.STATIC) == 0) {
  266. code.addAload(0);
  267. code.addLoad(1, field.getType());
  268. code.addPutfield(Bytecode.THIS, fieldName, fieldType);
  269. }
  270. else {
  271. code.addLoad(1, field.getType());
  272. code.addPutstatic(Bytecode.THIS, fieldName, fieldType);
  273. }
  274. code.addReturn(null);
  275. }
  276. catch (NotFoundException e) {
  277. throw new CannotCompileException(e);
  278. }
  279. minfo.setCodeAttribute(code.toCodeAttribute());
  280. CtClass cc = field.getDeclaringClass();
  281. // a stack map is not needed.
  282. return new CtMethod(minfo, cc);
  283. }
  284. /**
  285. * Creates a method forwarding to a delegate in
  286. * a super class. The created method calls a method specified
  287. * by <code>delegate</code> with all the parameters passed to the
  288. * created method. If the delegate method returns a value,
  289. * the created method returns that value to the caller.
  290. * The delegate method must be declared in a super class.
  291. *
  292. * <p>The following method is an example of the created method.
  293. *
  294. * <pre>
  295. * int f(int p, int q) {
  296. * return super.f(p, q);
  297. * }</pre>
  298. *
  299. * <p>The name of the created method can be changed by
  300. * <code>setName()</code>.
  301. *
  302. * @param delegate the method that the created method forwards to.
  303. * @param declaring the class to which the created method is
  304. * added.
  305. */
  306. public static CtMethod delegator(CtMethod delegate, CtClass declaring)
  307. throws CannotCompileException
  308. {
  309. try {
  310. return delegator0(delegate, declaring);
  311. }
  312. catch (NotFoundException e) {
  313. throw new CannotCompileException(e);
  314. }
  315. }
  316. private static CtMethod delegator0(CtMethod delegate, CtClass declaring)
  317. throws CannotCompileException, NotFoundException
  318. {
  319. MethodInfo deleInfo = delegate.getMethodInfo2();
  320. String methodName = deleInfo.getName();
  321. String desc = deleInfo.getDescriptor();
  322. ConstPool cp = declaring.getClassFile2().getConstPool();
  323. MethodInfo minfo = new MethodInfo(cp, methodName, desc);
  324. minfo.setAccessFlags(deleInfo.getAccessFlags());
  325. ExceptionsAttribute eattr = deleInfo.getExceptionsAttribute();
  326. if (eattr != null)
  327. minfo.setExceptionsAttribute(
  328. (ExceptionsAttribute)eattr.copy(cp, null));
  329. Bytecode code = new Bytecode(cp, 0, 0);
  330. boolean isStatic = Modifier.isStatic(delegate.getModifiers());
  331. CtClass deleClass = delegate.getDeclaringClass();
  332. CtClass[] params = delegate.getParameterTypes();
  333. int s;
  334. if (isStatic) {
  335. s = code.addLoadParameters(params, 0);
  336. code.addInvokestatic(deleClass, methodName, desc);
  337. }
  338. else {
  339. code.addLoad(0, deleClass);
  340. s = code.addLoadParameters(params, 1);
  341. code.addInvokespecial(deleClass, methodName, desc);
  342. }
  343. code.addReturn(delegate.getReturnType());
  344. code.setMaxLocals(++s);
  345. code.setMaxStack(s < 2 ? 2 : s); // for a 2-word return value
  346. minfo.setCodeAttribute(code.toCodeAttribute());
  347. // a stack map is not needed.
  348. return new CtMethod(minfo, declaring);
  349. }
  350. /**
  351. * Creates a wrapped method. The wrapped method receives parameters
  352. * in the form of an array of <code>Object</code>.
  353. *
  354. * <p>The body of the created method is a copy of the body of the method
  355. * specified by <code>body</code>. However, it is wrapped in
  356. * parameter-conversion code.
  357. *
  358. * <p>The method specified by <code>body</code> must have this singature:
  359. *
  360. * <pre>Object method(Object[] params, &lt;type&gt; cvalue)</pre>
  361. *
  362. * <p>The type of the <code>cvalue</code> depends on
  363. * <code>constParam</code>.
  364. * If <code>constParam</code> is <code>null</code>, the signature
  365. * must be:
  366. *
  367. * <pre>Object method(Object[] params)</pre>
  368. *
  369. * <p>The method body copied from <code>body</code> is wrapped in
  370. * parameter-conversion code, which converts parameters specified by
  371. * <code>parameterTypes</code> into an array of <code>Object</code>.
  372. * The returned value is also converted from the <code>Object</code>
  373. * type to the type specified by <code>returnType</code>. Thus,
  374. * the resulting method body is as follows:
  375. *
  376. * <pre>
  377. * Object[] params = new Object[] { p0, p1, ... };
  378. * &lt;<i>type</i>&gt; cvalue = &lt;<i>constant-value</i>&gt;;
  379. * <i>... copied method body ...</i>
  380. * Object result = &lt;<i>returned value</i>&gt;
  381. * return (<i>&lt;returnType&gt;</i>)result;
  382. * </pre>
  383. *
  384. * <p>The variables <code>p0</code>, <code>p2</code>, ... represent
  385. * formal parameters of the created method.
  386. * The value of <code>cvalue</code> is specified by
  387. * <code>constParam</code>.
  388. *
  389. * <p>If the type of a parameter or a returned value is a primitive
  390. * type, then the value is converted into a wrapper object such as
  391. * <code>java.lang.Integer</code>. If the type of the returned value
  392. * is <code>void</code>, the returned value is discarded.
  393. *
  394. * <p><i>Example:</i>
  395. *
  396. * <pre>
  397. * ClassPool pool = ... ;
  398. * CtClass vec = pool.makeClass("intVector");
  399. * vec.setSuperclass(pool.get("java.util.Vector"));
  400. * CtMethod addMethod = pool.getMethod("Sample", "add0");
  401. *
  402. * CtClass[] argTypes = { CtClass.intType };
  403. * CtMethod m = CtNewMethod.wrapped(CtClass.voidType, "add", argTypes,
  404. * null, addMethod, null, vec);
  405. * vec.addMethod(m);</pre>
  406. *
  407. * <p>where the class <code>Sample</code> is as follows:
  408. *
  409. * <pre>public class Sample extends java.util.Vector {
  410. * public Object add0(Object[] args) {
  411. * super.addElement(args[0]);
  412. * return null;
  413. * }
  414. * }</pre>
  415. *
  416. * <p>This program produces a class <code>intVector</code>:
  417. *
  418. * <pre>public class intVector extends java.util.Vector {
  419. * public void add(int p0) {
  420. * Object[] args = new Object[] { p0 };
  421. * // begin of the copied body
  422. * super.addElement(args[0]);
  423. * Object result = null;
  424. * // end
  425. * }
  426. * }</pre>
  427. *
  428. * <p>Note that the type of the parameter to <code>add()</code> depends
  429. * only on the value of <code>argTypes</code> passed to
  430. * <code>CtNewMethod.wrapped()</code>. Thus, it is easy to
  431. * modify this program to produce a
  432. * <code>StringVector</code> class, which is a vector containing
  433. * only <code>String</code> objects, and other vector classes.
  434. *
  435. * @param returnType the type of the returned value.
  436. * @param mname the method name.
  437. * @param parameterTypes a list of the parameter types.
  438. * @param exceptionTypes a list of the exception types.
  439. * @param body the method body
  440. * (must not be a static method).
  441. * @param constParam the constant parameter
  442. * (maybe <code>null</code>).
  443. * @param declaring the class to which the created method is
  444. * added.
  445. */
  446. public static CtMethod wrapped(CtClass returnType,
  447. String mname,
  448. CtClass[] parameterTypes,
  449. CtClass[] exceptionTypes,
  450. CtMethod body, ConstParameter constParam,
  451. CtClass declaring)
  452. throws CannotCompileException
  453. {
  454. return CtNewWrappedMethod.wrapped(returnType, mname, parameterTypes,
  455. exceptionTypes, body, constParam, declaring);
  456. }
  457. }