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

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