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.

JvstTest4.java 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. package javassist;
  2. import java.io.DataOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.util.HashSet;
  7. import javassist.bytecode.*;
  8. import javassist.bytecode.annotation.Annotation;
  9. import javassist.expr.*;
  10. public class JvstTest4 extends JvstTestRoot {
  11. public JvstTest4(String name) {
  12. super(name);
  13. }
  14. public void testInsertLocalVars() throws Exception {
  15. CtClass cc = sloader.get("test4.LocalVars");
  16. CtMethod m1 = cc.getDeclaredMethod("run");
  17. m1.getMethodInfo().getCodeAttribute().insertLocalVar(2, 20);
  18. m1.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile());
  19. CtMethod m2 = cc.getDeclaredMethod("run2");
  20. m2.getMethodInfo().getCodeAttribute().insertLocalVar(2, 0x101);
  21. m2.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile());
  22. cc.writeFile();
  23. Object obj = make(cc.getName());
  24. assertEquals(10, invoke(obj, "run"));
  25. assertEquals(10, invoke(obj, "run2"));
  26. }
  27. public void testCodeConv() throws Exception {
  28. CtClass cc = sloader.get("test4.CodeConv");
  29. CtMethod m1 = cc.getDeclaredMethod("m1");
  30. CtMethod m2 = cc.getDeclaredMethod("m2");
  31. CtMethod m3 = cc.getDeclaredMethod("m3");
  32. CodeConverter conv = new CodeConverter();
  33. conv.insertAfterMethod(m1, m3);
  34. conv.insertBeforeMethod(m2, m3);
  35. cc.instrument(conv);
  36. cc.writeFile();
  37. Object obj = make(cc.getName());
  38. assertEquals(111033, invoke(obj, "run"));
  39. }
  40. public void testCodeConv2() throws Exception {
  41. CtClass cc = sloader.get("test4.CodeConv2");
  42. CtField f = cc.getDeclaredField("field");
  43. CtField f2 = cc.getDeclaredField("sf");
  44. CtMethod run = cc.getDeclaredMethod("run");
  45. CodeConverter conv = new CodeConverter();
  46. conv.replaceFieldRead(f, cc, "read");
  47. conv.replaceFieldWrite(f, cc, "write");
  48. conv.replaceFieldRead(f2, cc, "read");
  49. conv.replaceFieldWrite(f2, cc, "write");
  50. run.instrument(conv);
  51. cc.writeFile();
  52. Object obj = make(cc.getName());
  53. assertEquals(14001600, invoke(obj, "run"));
  54. }
  55. public void testInsGap() throws Exception {
  56. CtClass cc = sloader.get("test4.GapSwitch");
  57. ExprEditor ed = new ExprEditor() {
  58. public void edit(MethodCall c) throws CannotCompileException {
  59. c.replace("{ value++; $_ = $proceed($$); }");
  60. }
  61. };
  62. CtMethod m1 = cc.getDeclaredMethod("run");
  63. m1.instrument(ed);
  64. CtMethod m2 = cc.getDeclaredMethod("run2");
  65. m2.instrument(ed);
  66. final CtMethod m3 = cc.getDeclaredMethod("run3");
  67. m3.instrument(new ExprEditor() {
  68. public void edit(MethodCall c) throws CannotCompileException {
  69. CodeIterator it = m3.getMethodInfo().getCodeAttribute().iterator();
  70. try {
  71. it.insertGap(c.indexOfBytecode(), 5000);
  72. } catch (BadBytecode e) {
  73. throw new CannotCompileException(e);
  74. }
  75. }
  76. });
  77. m3.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile());
  78. cc.writeFile();
  79. Object obj = make(cc.getName());
  80. assertEquals(1010, invoke(obj, "run"));
  81. assertEquals(1100, invoke(obj, "run2"));
  82. assertEquals(12222, invoke(obj, "run3"));
  83. }
  84. public void testAnnotationCheck() throws Exception {
  85. CtClass cc = sloader.get("test4.Anno");
  86. CtMethod m1 = cc.getDeclaredMethod("foo");
  87. CtField f = cc.getDeclaredField("value");
  88. assertTrue(cc.hasAnnotation(test4.Anno1.class));
  89. assertFalse(cc.hasAnnotation(java.lang.annotation.Documented.class));
  90. assertEquals("empty", ((test4.Anno1)cc.getAnnotation(test4.Anno1.class)).value());
  91. assertNull(cc.getAnnotation(Deprecated.class));
  92. assertTrue(m1.hasAnnotation(test4.Anno1.class));
  93. assertFalse(m1.hasAnnotation(java.lang.annotation.Documented.class));
  94. assertTrue(m1.getAnnotation(test4.Anno1.class) != null);
  95. assertNull(m1.getAnnotation(Deprecated.class));
  96. assertTrue(f.hasAnnotation(test4.Anno1.class));
  97. assertFalse(f.hasAnnotation(java.lang.annotation.Documented.class));
  98. assertTrue(f.getAnnotation(test4.Anno1.class) != null);
  99. assertNull(f.getAnnotation(Deprecated.class));
  100. }
  101. public void testRename() throws Exception {
  102. CtClass cc = sloader.get("test4.Rename");
  103. cc.setName("test4.Rename2");
  104. cc.rebuildClassFile();
  105. cc.writeFile();
  106. CtClass cc2 = sloader.get("test4.IRename");
  107. cc2.replaceClassName("test4.Rename", "test4.Rename2");
  108. cc2.rebuildClassFile();
  109. cc2.writeFile();
  110. Object obj = make(cc.getName());
  111. assertEquals("test4.Rename2", obj.getClass().getName());
  112. assertEquals(14, invoke(obj, "run"));
  113. }
  114. public void testRename2() throws Exception {
  115. CtClass cc = sloader.get("test4.Signature");
  116. cc.setName("test4.Sig");
  117. cc.rebuildClassFile();
  118. cc.writeFile();
  119. Object obj = make(cc.getName());
  120. assertEquals(3, invoke(obj, "run"));
  121. }
  122. public void testJIRA93() throws Exception {
  123. ClassPool cp = ClassPool.getDefault();
  124. CtClass cc = sloader.getCtClass("test4.JIRA93");
  125. CtMethod m = cc.getDeclaredMethod("foo");
  126. m.addLocalVariable("bar", CtClass.longType);
  127. // The original bug report includes the next line.
  128. // But this is not a bug.
  129. //m.insertAfter("bar;", true);
  130. // Instead, the following code is OK.
  131. m.insertBefore("bar = 0;");
  132. m.insertAfter("bar;", false);
  133. cc.writeFile();
  134. Object obj = make(cc.getName());
  135. }
  136. public void testNewRemover() throws Exception {
  137. CtClass cc = sloader.get("test4.NewRemover");
  138. CtMethod mth = cc.getDeclaredMethod("make");
  139. mth.getMethodInfo().rebuildStackMap(cc.getClassPool());
  140. mth.getMethodInfo().rebuildStackMapForME(cc.getClassPool());
  141. //cc.debugWriteFile("debug");
  142. CodeConverter conv = new CodeConverter();
  143. conv.replaceNew(cc, cc, "make2");
  144. mth.instrument(conv);
  145. cc.writeFile();
  146. Object obj = make(cc.getName());
  147. assertEquals(10, invoke(obj, "run"));
  148. }
  149. public void testClassFileWriter() throws Exception {
  150. ClassFileWriter cfw = new ClassFileWriter(ClassFile.JAVA_4, 0);
  151. ClassFileWriter.ConstPoolWriter cpw = cfw.getConstPool();
  152. ClassFileWriter.FieldWriter fw = cfw.getFieldWriter();
  153. fw.add(AccessFlag.PUBLIC, "value", "J", null);
  154. fw.add(AccessFlag.PROTECTED | AccessFlag.STATIC, "value2", "Ljava/lang/String;", null);
  155. ClassFileWriter.MethodWriter mw = cfw.getMethodWriter();
  156. mw.begin(AccessFlag.PUBLIC, MethodInfo.nameInit, "()V", null, null);
  157. assertEquals(0, mw.size());
  158. mw.add(Opcode.ALOAD_0);
  159. assertEquals(1, mw.size());
  160. mw.addInvoke(Opcode.INVOKESPECIAL, "java/lang/Object", MethodInfo.nameInit, "()V");
  161. mw.add(Opcode.RETURN);
  162. mw.codeEnd(1, 1);
  163. mw.end(null, null);
  164. mw.begin(AccessFlag.PUBLIC, "move", "(II)V", null, null);
  165. assertEquals(0, mw.size());
  166. mw.add(Opcode.ALOAD_0);
  167. mw.addInvoke(Opcode.INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
  168. assertEquals(4, mw.size());
  169. mw.add(Opcode.POP);
  170. mw.add(Opcode.RETURN);
  171. mw.add(Opcode.POP);
  172. mw.add(Opcode.RETURN);
  173. mw.codeEnd(1, 3);
  174. mw.addCatch(0, 4, 6, cpw.addClassInfo("java/lang/Exception"));
  175. mw.addCatch(0, 4, 6, cpw.addClassInfo("java/lang/Throwable"));
  176. mw.end(null, null);
  177. String[] exceptions = { "java/lang/Exception", "java/lang/NullPointerException" };
  178. mw.begin(AccessFlag.PUBLIC, "move2", "()V", exceptions, null);
  179. mw.add(Opcode.RETURN);
  180. mw.codeEnd(0, 1);
  181. StackMapTable.Writer stack = new StackMapTable.Writer(32);
  182. stack.sameFrame(1);
  183. mw.end(stack, null);
  184. mw.begin(AccessFlag.PUBLIC, "foo", "()I", null, null);
  185. mw.add(Opcode.ICONST_2);
  186. mw.add(Opcode.IRETURN);
  187. mw.codeEnd(1, 1);
  188. mw.end(null, null);
  189. byte[] out = cfw.end(AccessFlag.PUBLIC, cpw.addClassInfo("test4/WrittenFile"),
  190. cpw.addClassInfo("java/lang/Object"),
  191. null, null);
  192. FileOutputStream fos = new FileOutputStream("test4/WrittenFile.class");
  193. fos.write(out);
  194. fos.close();
  195. Object obj = make("test4.WrittenFile");
  196. assertNotNull(obj);
  197. assertEquals(2, invoke(obj, "foo"));
  198. }
  199. public void testClassFileWriter2() throws Exception {
  200. ClassFileWriter cfw = new ClassFileWriter(ClassFile.JAVA_4, 0);
  201. ClassFileWriter.ConstPoolWriter cpw = cfw.getConstPool();
  202. ClassFileWriter.FieldWriter fw = cfw.getFieldWriter();
  203. fw.add(AccessFlag.PUBLIC | AccessFlag.STATIC, "value", "I", null);
  204. ClassFileWriter.MethodWriter mw = cfw.getMethodWriter();
  205. mw.begin(AccessFlag.PUBLIC, MethodInfo.nameInit, "()V", null, null);
  206. mw.add(Opcode.ALOAD_0);
  207. mw.addInvoke(Opcode.INVOKESPECIAL, "java/lang/Object", MethodInfo.nameInit, "()V");
  208. mw.add(Opcode.RETURN);
  209. mw.codeEnd(1, 1);
  210. mw.end(null, null);
  211. String[] exceptions = { "java/lang/Exception" };
  212. mw.begin(AccessFlag.PUBLIC | AccessFlag.ABSTRACT, "move", "(II)V", exceptions, null);
  213. mw.end(null, null);
  214. int thisClass = cpw.addClassInfo("test4/WrittenFile2");
  215. int superClass = cpw.addClassInfo("java/lang/Object");
  216. cfw.end(new DataOutputStream(new FileOutputStream("test4/WrittenFile2.class")),
  217. AccessFlag.PUBLIC | AccessFlag.ABSTRACT, thisClass, superClass,
  218. null, null);
  219. File f = new File("test4/WrittenFile2.class");
  220. byte[] file = new byte[(int)f.length()];
  221. FileInputStream fis = new FileInputStream(f);
  222. fis.read(file);
  223. fis.close();
  224. byte[] out = cfw.end(AccessFlag.PUBLIC | AccessFlag.ABSTRACT, thisClass,
  225. superClass, null, null);
  226. assertEquals(out.length, file.length);
  227. for (int i = 0; i < out.length; i++)
  228. assertEquals(out[i], file[i]);
  229. CtClass sub = dloader.makeClass("test4.WrittenFile2sub", dloader.get("test4.WrittenFile2"));
  230. sub.addMethod(CtMethod.make("public void move(int i, int j) {}", sub));
  231. sub.addMethod(CtMethod.make("public int foo() { move(0, 1); return 1; }", sub));
  232. sub.writeFile();
  233. Object obj = make("test4.WrittenFile2sub");
  234. assertEquals(1, invoke(obj, "foo"));
  235. }
  236. public void testClassFileWriter3() throws Exception {
  237. ClassFileWriter cfw = new ClassFileWriter(ClassFile.JAVA_4, 0);
  238. ClassFileWriter.ConstPoolWriter cpw = cfw.getConstPool();
  239. int superClass = cpw.addClassInfo("java/lang/Object");
  240. final int syntheticTag = cpw.addUtf8Info("Synthetic");
  241. ClassFileWriter.AttributeWriter attribute = new ClassFileWriter.AttributeWriter() {
  242. public void write(DataOutputStream out) throws java.io.IOException {
  243. out.writeShort(syntheticTag);
  244. out.writeInt(0);
  245. }
  246. public int size() {
  247. return 1;
  248. }
  249. };
  250. ClassFileWriter.FieldWriter fw = cfw.getFieldWriter();
  251. fw.add(AccessFlag.PUBLIC, "value", "J", null);
  252. fw.add(AccessFlag.PROTECTED | AccessFlag.STATIC, "value2", "Ljava/lang/String;", attribute);
  253. ClassFileWriter.MethodWriter mw = cfw.getMethodWriter();
  254. mw.begin(AccessFlag.PUBLIC, MethodInfo.nameInit, "()V", null, attribute);
  255. mw.add(Opcode.ALOAD_0);
  256. mw.add(Opcode.INVOKESPECIAL);
  257. mw.add16(cpw.addMethodrefInfo(superClass, cpw.addNameAndTypeInfo(MethodInfo.nameInit, "()V")));
  258. // mw.addInvoke(Opcode.INVOKESPECIAL, "java/lang/Object", MethodInfo.nameInit, "()V");
  259. mw.add(Opcode.RETURN);
  260. mw.codeEnd(1, 1);
  261. mw.end(null, null);
  262. mw.begin(AccessFlag.PUBLIC, "foo", "()I", null, attribute);
  263. mw.add(Opcode.ICONST_2);
  264. mw.add(Opcode.IRETURN);
  265. mw.codeEnd(1, 1);
  266. mw.end(null, null);
  267. int thisClass = cpw.addClassInfo("test4/WrittenFile3");
  268. cfw.end(new DataOutputStream(new FileOutputStream("test4/WrittenFile3.class")),
  269. AccessFlag.PUBLIC, thisClass, superClass,
  270. null, attribute);
  271. File f = new File("test4/WrittenFile3.class");
  272. byte[] file = new byte[(int)f.length()];
  273. FileInputStream fis = new FileInputStream(f);
  274. fis.read(file);
  275. fis.close();
  276. byte[] out = cfw.end(AccessFlag.PUBLIC, thisClass, superClass,
  277. null, attribute);
  278. assertEquals(out.length, file.length);
  279. for (int i = 0; i < out.length; i++)
  280. assertEquals(out[i], file[i]);
  281. Object obj = make("test4.WrittenFile3");
  282. assertNotNull(obj);
  283. assertEquals(2, invoke(obj, "foo"));
  284. }
  285. public void testCtArray() throws Exception {
  286. CtClass cc = sloader.get("int");
  287. assertEquals(Modifier.FINAL | Modifier.PUBLIC, cc.getModifiers());
  288. cc = sloader.get("int[]");
  289. assertEquals(Modifier.FINAL | Modifier.PUBLIC, cc.getModifiers());
  290. cc = sloader.get("java.lang.String[]");
  291. assertEquals(Modifier.FINAL | Modifier.PUBLIC, cc.getModifiers());
  292. CtClass[] intfs = cc.getInterfaces();
  293. assertEquals(Cloneable.class.getName(), intfs[0].getName());
  294. assertEquals(java.io.Serializable.class.getName(), intfs[1].getName());
  295. cc = sloader.get("test4.CtArrayTest[]");
  296. assertEquals(Modifier.FINAL | Modifier.PUBLIC, cc.getModifiers());
  297. }
  298. public void testAnalysisType() throws Exception {
  299. testAnalysisType2(sloader.get("int[]"), 1);
  300. testAnalysisType2(sloader.get("java.lang.String[][]"), 2);
  301. sloader.makeClass("A");
  302. testAnalysisType2(sloader.getCtClass("A"), 0);
  303. testAnalysisType2(sloader.getCtClass("A[]"), 1);
  304. testAnalysisType2(sloader.getCtClass("A[][]"), 2);
  305. }
  306. private void testAnalysisType2(CtClass cc, int size) throws Exception {
  307. javassist.bytecode.analysis.Type t = javassist.bytecode.analysis.Type.get(cc);
  308. assertEquals(cc.getName(), size, t.getDimensions());
  309. }
  310. public void testArrayType() throws Exception {
  311. CtClass at = sloader.get("java.lang.Object[]");
  312. CtClass[] intfs = at.getInterfaces();
  313. assertEquals(intfs.length, 2);
  314. assertEquals(intfs[0].getName(), java.lang.Cloneable.class.getName());
  315. assertEquals(intfs[1].getName(), java.io.Serializable.class.getName());
  316. assertTrue(at.subtypeOf(sloader.get(java.lang.Object.class.getName())));
  317. assertTrue(at.subtypeOf(intfs[0]));
  318. assertTrue(at.subtypeOf(intfs[1]));
  319. assertTrue(at.subtypeOf(intfs[1]));
  320. CtClass subt = sloader.get(java.text.CharacterIterator.class.getName());
  321. assertFalse(at.subtypeOf(subt));
  322. }
  323. public void testGetFieldDesc() throws Exception {
  324. CtClass cc = sloader.get("test4.GetFieldDesc");
  325. cc.getDeclaredField("f", "I");
  326. cc.getField("s", "Ljava/lang/String;");
  327. CtClass cc2 = sloader.get("test4.GetFieldDescSub");
  328. assertEquals(cc2.getField("s", "Ljava/lang/String;").getDeclaringClass().getName(),
  329. "test4.GetFieldDesc");
  330. assertEquals(cc2.getField("s", "I").getDeclaringClass().getName(),
  331. "test4.GetFieldDescSub");
  332. }
  333. public void testMakeMethod() throws CannotCompileException {
  334. CtClass ctClass = sloader.makeClass("test4.MakeMethod2");
  335. CtNewMethod.make("public String foox(){return test4.MakeMethod.foo();}", ctClass);
  336. CtNewMethod.make("public String foo(){return test4.MakeMethod.foo();}", ctClass);
  337. }
  338. public void testVarArgs() throws Exception {
  339. CtClass cc = sloader.get("test4.VarArgs");
  340. CtMethod m = CtMethod.make("public int foo(int i, String[] args) { return args.length; }", cc);
  341. m.setModifiers(m.getModifiers() | Modifier.VARARGS);
  342. cc.addMethod(m);
  343. m = CtMethod.make("public int run() { return goo(7, new int[] { 1, 2, 3 }); }", cc);
  344. cc.addMethod(m);
  345. cc.writeFile();
  346. Object obj = make(cc.getName());
  347. assertEquals(3, invoke(obj, "run"));
  348. }
  349. public void testGetAllRef() throws Exception {
  350. CtClass cc = sloader.get("test4.GetAllRef");
  351. ClassFile cf = cc.getClassFile();
  352. AttributeInfo ainfo
  353. = cf.getAttribute(AnnotationsAttribute.visibleTag);
  354. ClassMap map = new ClassMap();
  355. map.put("test4.GetAllRefAnno", "test4.GetAllRefAnno2");
  356. map.put("test4.GetAllRefEnum", "test4.GetAllRefEnum2");
  357. map.put("java.lang.String", "java.lang.StringBuilder");
  358. cf.addAttribute(ainfo.copy(cf.getConstPool(), map));
  359. cc.writeFile();
  360. cc.detach();
  361. cc = dloader.get(cc.getName());
  362. test4.GetAllRefAnno2 anno
  363. = (test4.GetAllRefAnno2)cc.getAnnotation(test4.GetAllRefAnno2.class);
  364. assertEquals(test4.GetAllRefEnum2.A, anno.getA());
  365. assertEquals(StringBuilder.class, anno.getC());
  366. }
  367. public void testGetAllRefB() throws Exception {
  368. CtClass cc = sloader.get("test4.GetAllRefB");
  369. ClassMap map = new ClassMap();
  370. map.put("test4.GetAllRefAnno", "test4.GetAllRefAnno2");
  371. map.put("test4.GetAllRefEnum", "test4.GetAllRefEnum2");
  372. map.put("java.lang.String", "java.lang.StringBuilder");
  373. cc.replaceClassName(map);
  374. //cc.replaceClassName("test4.GetAllRefAnno", "test4.GetAllRefAnno2");
  375. cc.writeFile();
  376. cc = dloader.get(cc.getName());
  377. test4.GetAllRefAnno2 anno
  378. = (test4.GetAllRefAnno2)cc.getAnnotation(test4.GetAllRefAnno2.class);
  379. assertEquals(test4.GetAllRefEnum2.A, anno.getA());
  380. assertEquals(StringBuilder.class, anno.getC());
  381. /*
  382. AnnotationsAttribute aainfo = (AnnotationsAttribute)
  383. cc.getClassFile().getAttribute(AnnotationsAttribute.visibleTag);
  384. Annotation[] a = aainfo.getAnnotations();
  385. System.err.println(a[0].getTypeName());
  386. System.err.println(a[0]);
  387. */
  388. }
  389. public void testGetAllRefC() throws Exception {
  390. CtClass cc = sloader.get("test4.GetAllRefC");
  391. HashSet set = new HashSet();
  392. set.add("java.lang.Object");
  393. set.add("java.lang.String");
  394. set.add("test4.GetAllRefC");
  395. set.add("test4.GetAllRefAnno");
  396. set.add("test4.GetAllRefEnum");
  397. set.add("test4.GetAllRefAnnoC");
  398. set.add("test4.GetAllRefAnnoC2");
  399. set.add("test4.GetAllRefAnnoC3");
  400. set.add("test4.GetAllRefAnnoC4");
  401. java.util.Collection<String> refs
  402. = (java.util.Collection<String>)cc.getRefClasses();
  403. assertEquals(set.size(), refs.size());
  404. for (String s: refs) {
  405. assertTrue(set.contains(s));
  406. }
  407. }
  408. public void testGetAllRefInner() throws Exception {
  409. HashSet set = new HashSet();
  410. set.add("java.lang.Object");
  411. set.add("test4.GetAllRefInnerTest");
  412. set.add("test4.GetAllRefInnerTest$1");
  413. set.add("test4.GetAllRefInnerTest$2");
  414. CtClass cc = sloader.get("test4.GetAllRefInnerTest");
  415. int size = 0;
  416. for (Object s: cc.getRefClasses()) {
  417. assertTrue((String)s, set.contains(s));
  418. ++size;
  419. }
  420. assertEquals(set.size(), size);
  421. }
  422. public void testNestedClass() throws Exception {
  423. CtClass cc = sloader.get("test4.NestedClass$1");
  424. CtClass[] tab = cc.getNestedClasses();
  425. assertEquals(1, tab.length);
  426. assertEquals("test4.NestedClass$1$1", tab[0].getName());
  427. cc = sloader.get("test4.NestedClass$1$1");
  428. tab = cc.getNestedClasses();
  429. assertEquals(0, tab.length);
  430. cc = sloader.get("test4.NestedClass");
  431. tab = cc.getNestedClasses();
  432. for (CtClass c: tab) {
  433. System.err.println(c.getName());
  434. }
  435. // Eclipse compiler sets tab.length to 4 but javac sets to 3.
  436. assertTrue(tab.length == 4 || tab.length == 3);
  437. for (CtClass c: tab) {
  438. String name = c.getName();
  439. assertTrue(name.equals("test4.NestedClass$N")
  440. || name.equals("test4.NestedClass$S")
  441. || name.equals("test4.NestedClass$1")
  442. || name.equals("test4.NestedClass$1In"));
  443. }
  444. cc = sloader.get("test4.NestedClass$1In");
  445. tab = cc.getNestedClasses();
  446. assertEquals(0, tab.length);
  447. }
  448. public void testGetClasses() throws Exception {
  449. CtClass cc = sloader.get("test4.NestedClass");
  450. CtClass[] tab = cc.getDeclaredClasses();
  451. // Eclipse compiler sets tab.length to 4 but javac sets to 3.
  452. assertTrue(tab.length == 4 || tab.length == 3);
  453. for (CtClass c: tab) {
  454. String name = c.getName();
  455. assertTrue(name.equals("test4.NestedClass$N")
  456. || name.equals("test4.NestedClass$S")
  457. || name.equals("test4.NestedClass$1")
  458. || name.equals("test4.NestedClass$1In"));
  459. }
  460. cc = sloader.get("test4.NestedClass$1In");
  461. tab = cc.getDeclaredClasses();
  462. assertEquals(0, tab.length);
  463. }
  464. public void testImportPac() throws Exception {
  465. CtClass cc = sloader.makeClass("test4.TestImpP");
  466. sloader.importPackage("test4.NewImportPac");
  467. try {
  468. cc.addMethod(CtNewMethod.make(
  469. "public int foo(){ " +
  470. " ImportPac obj = new ImportPac();" +
  471. " return obj.getClass().getName().length(); }", cc));
  472. fail("ImportPac was found");
  473. }
  474. catch (CannotCompileException e) {}
  475. cc.addMethod(CtNewMethod.make(
  476. "public int bar(){ " +
  477. " NewImportPac obj = new NewImportPac();" +
  478. " return obj.getClass().getName().length(); }", cc));
  479. sloader.clearImportedPackages();
  480. }
  481. public void testLength() throws Exception {
  482. CtClass cc = sloader.makeClass("test4.LengthTest");
  483. cc.addMethod(CtNewMethod.make(
  484. "public int len(String s){ " +
  485. " return s.length(); }", cc));
  486. cc.addField(CtField.make("int length = 100;", cc));
  487. cc.addConstructor(CtNewConstructor.defaultConstructor(cc));
  488. cc.addMethod(CtNewMethod.make(
  489. "public int run(){ " +
  490. " test4.LengthTest t = new test4.LengthTest();" +
  491. " return len(\"foo\") + t.length + test4.length.m(); }", cc));
  492. try {
  493. cc.addMethod(CtNewMethod.make(
  494. "public int run(){ " +
  495. " return test4no.length.m(); }", cc));
  496. fail("test4no was found!");
  497. }
  498. catch (CannotCompileException e) {
  499. System.out.println(e);
  500. }
  501. cc.writeFile();
  502. Object obj = make(cc.getName());
  503. assertEquals(110, invoke(obj, "run"));
  504. }
  505. public void testAaload() throws Exception {
  506. CtClass clazz = sloader.get("test4.Aaload");
  507. CtMethod method = clazz.getMethod("narf", "()V");
  508. method.instrument(new ExprEditor() {
  509. @Override
  510. public void edit(MethodCall call) throws CannotCompileException {
  511. String name = call.getMethodName();
  512. if (name.equals("addActionListener"))
  513. call.replace("$0." + name + "($$);");
  514. }
  515. });
  516. }
  517. public void testPackage() throws Throwable { // JASSIST-147
  518. String packageName = "test4.pack";
  519. ClassPool pool = ClassPool.getDefault();
  520. pool.makePackage(pool.getClassLoader(), packageName);
  521. pool.makePackage(pool.getClassLoader(), packageName);
  522. CtClass ctcl = pool.makeClass("test4.pack.Clazz");
  523. Class cl = ctcl.toClass();
  524. Object obj = cl.newInstance();
  525. assertEquals(packageName, obj.getClass().getPackage().getName());
  526. }
  527. public static final String BASE_PATH = "../";
  528. public static final String JAVASSIST_JAR = BASE_PATH + "javassist.jar";
  529. public static final String CLASSES_FOLDER = BASE_PATH + "build/classes";
  530. public static final String TEST_CLASSES_FOLDER = BASE_PATH + "build/test-classes";
  531. public static class Inner1 {
  532. public static int get() {
  533. return 0;
  534. }
  535. }
  536. public void testJIRA150() throws Exception {
  537. ClassPool pool = new ClassPool(true);
  538. for(int paths=0; paths<50; paths++) {
  539. pool.appendClassPath(JAVASSIST_JAR);
  540. pool.appendClassPath(CLASSES_FOLDER);
  541. pool.appendClassPath(TEST_CLASSES_FOLDER);
  542. }
  543. CtClass cc = pool.get("Jassist150$Inner1");
  544. CtMethod ccGet = cc.getDeclaredMethod("get");
  545. long startTime = System.currentTimeMillis();
  546. for(int replace=0; replace<1000; replace++) {
  547. ccGet.setBody(
  548. "{ int n1 = java.lang.Integer#valueOf(1); " +
  549. " int n2 = java.lang.Integer#valueOf(2); " +
  550. " int n3 = java.lang.Integer#valueOf(3); " +
  551. " int n4 = java.lang.Integer#valueOf(4); " +
  552. " int n5 = java.lang.Integer#valueOf(5); " +
  553. " return n1+n2+n3+n4+n5; }");
  554. }
  555. long endTime = System.currentTimeMillis();
  556. for(int replace=0; replace<1000; replace++) {
  557. ccGet.setBody(
  558. "{ int n1 = java.lang.Integer.valueOf(1); " +
  559. " int n2 = java.lang.Integer.valueOf(2); " +
  560. " int n3 = java.lang.Integer.valueOf(3); " +
  561. " int n4 = java.lang.Integer.valueOf(4); " +
  562. " int n5 = java.lang.Integer.valueOf(5); " +
  563. " return n1+n2+n3+n4+n5; }");
  564. }
  565. long endTime2 = System.currentTimeMillis();
  566. for(int replace=0; replace<1000; replace++) {
  567. ccGet.setBody(
  568. "{ int n1 = Integer.valueOf(1); " +
  569. " int n2 = Integer.valueOf(2); " +
  570. " int n3 = Integer.valueOf(3); " +
  571. " int n4 = Integer.valueOf(4); " +
  572. " int n5 = Integer.valueOf(5); " +
  573. " return n1+n2+n3+n4+n5; }");
  574. }
  575. long endTime3 = System.currentTimeMillis();
  576. long t1 = endTime - startTime;
  577. long t2 = endTime2 - endTime;
  578. long t3 = endTime3 - endTime2;
  579. System.out.println("JIRA150: " + t1 + ", " + t2 + ", " + t3);
  580. assertTrue("performance test (the next try may succeed): " + t1 + "/ 6 < " + t2,
  581. t2 < t1 * 6);
  582. assertTrue("", t3 < t1 * 3);
  583. }
  584. public void testJIRA150b() throws Exception {
  585. int origSize = javassist.compiler.MemberResolver.getInvalidMapSize();
  586. int N = 100;
  587. for (int k = 0; k < N; k++) {
  588. ClassPool pool = new ClassPool(true);
  589. for(int paths=0; paths<50; paths++) {
  590. pool.appendClassPath(JAVASSIST_JAR);
  591. pool.appendClassPath(CLASSES_FOLDER);
  592. pool.appendClassPath(TEST_CLASSES_FOLDER);
  593. }
  594. CtClass cc = pool.get("Jassist150$Inner1");
  595. CtMethod ccGet = cc.getDeclaredMethod("get");
  596. for(int replace=0; replace < 5; replace++) {
  597. ccGet.setBody(
  598. "{ int n1 = java.lang.Integer#valueOf(1); " +
  599. " int n2 = java.lang.Integer#valueOf(2); " +
  600. " int n3 = java.lang.Integer#valueOf(3); " +
  601. " int n4 = java.lang.Integer#valueOf(4); " +
  602. " int n5 = java.lang.Integer#valueOf(5); " +
  603. " return n1+n2+n3+n4+n5; }");
  604. }
  605. pool = null;
  606. }
  607. // try to run garbage collection.
  608. int[][] mem = new int[100][];
  609. int[] large;
  610. for (int i = 0; i < 100; i++) {
  611. large = new int[1000000];
  612. large[large.length - 2] = 9 + i;
  613. mem[i] = large;
  614. }
  615. System.gc();
  616. System.gc();
  617. int size = javassist.compiler.MemberResolver.getInvalidMapSize();
  618. System.out.println("JIRA150b " + size + " " + mem[mem.length - 1][mem[0].length - 2]);
  619. assertTrue("JIRA150b size: " + origSize + " " + size, size < origSize + N);
  620. }
  621. public void testJIRA152() throws Exception {
  622. CtClass cc = sloader.get("test4.JIRA152");
  623. CtMethod mth = cc.getDeclaredMethod("buildColumnOverride");
  624. //CtMethod mth = cc.getDeclaredMethod("tested");
  625. mth.instrument(new ExprEditor() {
  626. public void edit(MethodCall c) throws CannotCompileException {
  627. c.replace("try{ $_ = $proceed($$); } catch (Throwable t) { throw t; }");
  628. }
  629. });
  630. cc.writeFile();
  631. Object obj = make(cc.getName());
  632. assertEquals(1, invoke(obj, "test"));
  633. }
  634. public void testJIRA151() {
  635. // try it using classloader of TestDescForName Desc.useContextClassLoader = false;
  636. assertTrue(javassist.runtime.Desc.getClazz("[Ljava.lang.String;") != null);
  637. //Thread.currentThread().setContextClassLoader(TestDescForName.class.getClassLoader());
  638. boolean old = javassist.runtime.Desc.useContextClassLoader;
  639. javassist.runtime.Desc.useContextClassLoader = true;
  640. assertTrue(javassist.runtime.Desc.getClazz("[Ljava.lang.String;") != null);
  641. javassist.runtime.Desc.useContextClassLoader = old;
  642. }
  643. public void testJIRA166() throws Exception {
  644. CtClass cc = sloader.get("test4.JIRA166");
  645. cc.instrument(new ExprEditor() {
  646. public void edit(FieldAccess fa) throws CannotCompileException {
  647. if (fa.isReader() && fa.getFieldName().equals("length"))
  648. fa.replace("length = self().length + \"!\"; $_ = ($r) this.length.substring(1);");
  649. }
  650. });
  651. cc.writeFile();
  652. Object obj = make(cc.getName());
  653. assertEquals(1, invoke(obj, "run"));
  654. }
  655. public void testGenericSignature() throws Exception {
  656. CtClass cc = sloader.makeClass("test4.GenSig");
  657. CtClass objClass = sloader.get(CtClass.javaLangObject);
  658. SignatureAttribute.ClassSignature cs
  659. = new SignatureAttribute.ClassSignature(
  660. new SignatureAttribute.TypeParameter[] {
  661. new SignatureAttribute.TypeParameter("T") });
  662. cc.setGenericSignature(cs.encode()); // <T:Ljava/lang/Object;>Ljava/lang/Object;
  663. CtField f = new CtField(objClass, "value", cc);
  664. SignatureAttribute.TypeVariable tvar = new SignatureAttribute.TypeVariable("T");
  665. f.setGenericSignature(tvar.encode()); // TT;
  666. cc.addField(f);
  667. CtMethod m = CtNewMethod.make("public Object get(){return value;}", cc);
  668. SignatureAttribute.MethodSignature ms
  669. = new SignatureAttribute.MethodSignature(null, null, tvar, null);
  670. m.setGenericSignature(ms.encode()); // ()TT;
  671. cc.addMethod(m);
  672. CtMethod m2 = CtNewMethod.make("public void set(Object v){value = v;}", cc);
  673. SignatureAttribute.MethodSignature ms2
  674. = new SignatureAttribute.MethodSignature(null, new SignatureAttribute.Type[] { tvar },
  675. new SignatureAttribute.BaseType("void"), null);
  676. m2.setGenericSignature(ms2.encode()); // (TT;)V;
  677. cc.addMethod(m2);
  678. cc.writeFile();
  679. Object obj = make(cc.getName());
  680. Class clazz = obj.getClass();
  681. assertEquals("T", clazz.getTypeParameters()[0].getName());
  682. assertEquals("T", ((java.lang.reflect.TypeVariable)clazz.getDeclaredField("value").getGenericType()).getName());
  683. java.lang.reflect.Method rm = clazz.getDeclaredMethod("get", new Class[0]);
  684. assertEquals("T", ((java.lang.reflect.TypeVariable)rm.getGenericReturnType()).getName());
  685. java.lang.reflect.Method rm2 = clazz.getDeclaredMethod("set", new Class[] { Object.class });
  686. assertEquals("T", ((java.lang.reflect.TypeVariable)rm2.getGenericParameterTypes()[0]).getName());
  687. }
  688. public void testJIRA171() throws Exception {
  689. SignatureAttribute.MethodSignature ms
  690. = SignatureAttribute.toMethodSignature("(Ljava/lang/Object;Lorg/apache/hadoop/io/Text;"
  691. + "Lorg/apache/hadoop/mapreduce/Mapper<Ljava/lang/Object;Lorg/apache/hadoop/io/Text;"
  692. + "Lorg/apache/hadoop/io/Text;Lorg/apache/hadoop/io/IntWritable;>.Context;)V");
  693. String s = ms.toString();
  694. System.out.println(s);
  695. assertEquals("<> (java.lang.Object, org.apache.hadoop.io.Text, "
  696. + "org.apache.hadoop.mapreduce.Mapper<java.lang.Object, org.apache.hadoop.io.Text, "
  697. + "org.apache.hadoop.io.Text, org.apache.hadoop.io.IntWritable>.Context) void", s);
  698. }
  699. public void testAfter() throws Exception {
  700. CtClass cc = sloader.get("test4.AfterTest");
  701. CtMethod m1 = cc.getDeclaredMethod("m1");
  702. m1.insertAfter("print();");
  703. CtMethod m2 = cc.getDeclaredMethod("m2");
  704. m2.insertAfter("print();");
  705. CtMethod m3 = cc.getDeclaredMethod("m3");
  706. m3.insertAfter("print();");
  707. CtMethod m4 = cc.getDeclaredMethod("m4");
  708. m4.insertAfter("print();");
  709. CtMethod mm1 = cc.getDeclaredMethod("mm1");
  710. mm1.insertAfter("print();", true);
  711. CtMethod mm2 = cc.getDeclaredMethod("mm2");
  712. mm2.insertAfter("print();", true);
  713. CtMethod mm3 = cc.getDeclaredMethod("mm3");
  714. mm3.insertAfter("print();", true);
  715. CtMethod mm4 = cc.getDeclaredMethod("mm4");
  716. mm4.insertAfter("print();", true);
  717. cc.writeFile();
  718. Object obj = make(cc.getName());
  719. assertEquals(131, invoke(obj, "test1"));
  720. assertEquals(112, invoke(obj, "test2"));
  721. assertEquals(10, invoke(obj, "test3"));
  722. assertEquals(100, invoke(obj, "test4"));
  723. assertEquals(131, invoke(obj, "test11"));
  724. assertEquals(112, invoke(obj, "test22"));
  725. assertEquals(10, invoke(obj, "test33"));
  726. assertEquals(100, invoke(obj, "test44"));
  727. }
  728. public void testJIRA186() throws Exception {
  729. CtClass cc = sloader.get("test4.JIRA186");
  730. cc.getDeclaredMethod("test").insertBefore("{" +
  731. " java.util.List l = new java.util.ArrayList();" +
  732. " l.add(this.toString());" +
  733. "}");
  734. cc.writeFile();
  735. Object obj = make(cc.getName());
  736. assertEquals(1, invoke(obj, "test"));
  737. }
  738. // JASSIST-190
  739. public void testMultipleCatch() throws Exception {
  740. CtClass cc = sloader.get("test4.MultiCatch");
  741. CtMethod m1 = cc.getDeclaredMethod("m1");
  742. m1.insertAfter("print();");
  743. cc.writeFile();
  744. Object obj = make(cc.getName());
  745. assertEquals(12, invoke(obj, "test1"));
  746. }
  747. // JASSIST-185
  748. public void testLocalVariableTypeTable() throws Exception {
  749. CtClass cc = sloader.get("test4.Lvtt");
  750. CtMethod m = cc.getDeclaredMethod("run");
  751. m.addParameter(CtClass.intType);
  752. cc.writeFile();
  753. Object obj = make(cc.getName());
  754. }
  755. // JASSISt-181
  756. public void testAnnotationWithGenerics() throws Exception {
  757. CtClass cc0 = sloader.get("test4.JIRA181b");
  758. CtField field0 = cc0.getField("aField");
  759. String s0 = field0.getAnnotation(test4.JIRA181b.Condition.class).toString();
  760. assertEquals("@test4.JIRA181b$Condition(condition=java.lang.String.class)", s0);
  761. CtField field01 = cc0.getField("aField2");
  762. String s01 = field01.getAnnotation(test4.JIRA181b.Condition.class).toString();
  763. assertEquals("@test4.JIRA181b$Condition(condition=void.class)", s01);
  764. CtClass cc = sloader.get("test4.JIRA181");
  765. CtField field = cc.getField("aField");
  766. String s = field.getAnnotation(test4.JIRA181.Condition.class).toString();
  767. assertEquals("@test4.JIRA181$Condition(condition=test4.JIRA181<T>.B.class)", s);
  768. CtField field2 = cc.getField("aField2");
  769. String s2 = field2.getAnnotation(test4.JIRA181.Condition2.class).toString();
  770. assertEquals("@test4.JIRA181$Condition2(condition=test4.JIRA181<T>.B[].class)", s2);
  771. }
  772. public void testJIRA195() throws Exception {
  773. CtClass cc = sloader.get("test4.JIRA195");
  774. CtMethod mth = cc.getDeclaredMethod("test");
  775. mth.getMethodInfo().rebuildStackMap(cc.getClassPool());
  776. cc.writeFile();
  777. Object obj = make(cc.getName());
  778. assertEquals(4, invoke(obj, "run"));
  779. }
  780. public void testJIRA188() throws Exception {
  781. CtClass cc = sloader.makeClass("test4.JIRA188");
  782. CtField f = new CtField(CtClass.intType, "f", cc);
  783. f.setModifiers(Modifier.PRIVATE);
  784. cc.addField(f);
  785. cc.addMethod(CtNewMethod.make(
  786. "public int getf(test4.JIRA188 p){ return p.f; }", cc));
  787. cc.detach();
  788. // System.gc();
  789. try {
  790. cc = sloader.get("test4.JIRA188");
  791. fail("test4.JIRA188 found");
  792. }
  793. catch (NotFoundException e) {}
  794. cc = sloader.makeClass("test4.JIRA188");
  795. cc.addField(new CtField(CtClass.intType, "g", cc));
  796. cc.addMethod(CtNewMethod.make(
  797. "public int getf(test4.JIRA188 p){ return p.g; }", cc));
  798. }
  799. public void testJIRA158() throws Exception {
  800. CtClass cc = sloader.get("test4.JIRA158");
  801. cc.addMethod(CtMethod.make("public int run() { return obj.foo(jj, dd) + obj.bar(j, d); }", cc));
  802. cc.writeFile();
  803. Object obj = make(cc.getName());
  804. assertEquals(15, invoke(obj, "run"));
  805. }
  806. public void testJIRA207() throws Exception {
  807. CtClass cc = sloader.get("test4.JIRA207");
  808. CtMethod cm = cc.getDeclaredMethod("foo");
  809. cm.insertBefore("throw new Exception();");
  810. CtMethod cm2 = cc.getDeclaredMethod("run2");
  811. cm2.insertBefore("throw new Exception();");
  812. cc.writeFile();
  813. Object obj = make(cc.getName());
  814. try {
  815. invoke(obj, "run2");
  816. fail("run2");
  817. }
  818. catch (Exception e) {}
  819. }
  820. public void testJIRA212() throws Exception {
  821. CtClass cc = sloader.get("test4.JIRA212");
  822. for (final CtBehavior behavior : cc.getDeclaredBehaviors()) {
  823. behavior.instrument(new ExprEditor() {
  824. public void edit(FieldAccess fieldAccess) throws CannotCompileException {
  825. String fieldName = fieldAccess.getFieldName().substring(0,1).toUpperCase() + fieldAccess.getFieldName().substring(1);
  826. if (fieldAccess.isReader()) {
  827. // Rewrite read access
  828. fieldAccess.replace("$_ = $0.get" + fieldName + "();");
  829. } else if (fieldAccess.isWriter()) {
  830. // Rewrite write access
  831. fieldAccess.replace("$0.set" + fieldName + "($1);");
  832. }
  833. }});
  834. }
  835. cc.writeFile();
  836. Object obj = make(cc.getName());
  837. }
  838. public void testWhileTrueKO() throws Exception {
  839. final ClassPool pool = ClassPool.getDefault();
  840. final CtClass cc = pool.makeClass("test4.TestWhileTrueKO");
  841. String source = "public void testWhile() { while(true) { break; } }";
  842. cc.addMethod(CtMethod.make(source, cc));
  843. cc.writeFile();
  844. make(cc.getName());
  845. }
  846. public void testWhileTrueOK() throws Exception {
  847. final ClassPool pool = ClassPool.getDefault();
  848. final CtClass cc = pool.makeClass("test4.TestWhileTrueOK");
  849. String source = "public void testWhile() { while(0==0) { break; }}";
  850. cc.addMethod(CtMethod.make(source, cc));
  851. cc.writeFile();
  852. make(cc.getName());
  853. }
  854. // JIRA JASSIST-224
  855. public void testMethodParameters() throws Exception {
  856. Class rc = test4.MethodParamTest.class;
  857. java.lang.reflect.Method m = rc.getDeclaredMethods()[0];
  858. java.lang.reflect.Parameter[] params = m.getParameters();
  859. assertEquals("i", params[0].getName());
  860. assertEquals("s", params[1].getName());
  861. CtClass cc = sloader.get("test4.MethodParamTest");
  862. ClassFile cf = cc.getClassFile2();
  863. ConstPool cp = cf.getConstPool();
  864. MethodInfo minfo = cf.getMethod("test");
  865. MethodParametersAttribute attr
  866. = (MethodParametersAttribute)minfo.getAttribute(MethodParametersAttribute.tag);
  867. assertEquals(2, attr.size());
  868. assertEquals("i", cp.getUtf8Info(attr.name(0)));
  869. assertEquals("s", cp.getUtf8Info(attr.name(1)));
  870. attr = (MethodParametersAttribute)attr.copy(cp, null);
  871. assertEquals(2, attr.size());
  872. assertEquals("i", cp.getUtf8Info(attr.name(0)));
  873. assertEquals("s", cp.getUtf8Info(attr.name(1)));
  874. }
  875. // JIRA JASSIST-220
  876. public void testStaticInterfaceMethods() throws Exception {
  877. CtClass cc = sloader.get("test4.JIRA220");
  878. cc.getMethod("foo", "()V").instrument(new ExprEditor() {
  879. @Override
  880. public void edit(MethodCall m) throws CannotCompileException {
  881. try {
  882. m.getClassName();
  883. } catch (Exception e) {
  884. fail(e.getMessage());
  885. }
  886. }
  887. });
  888. }
  889. // JIRA-230
  890. public void testDeadcode() throws Exception {
  891. CtClass newClass = sloader.makeClass("test4.TestDeadcode");
  892. addDeadCode(newClass, "public void evaluate(){if (false) {int i = 0;}}");
  893. addDeadCode(newClass, "public void evaluate2(){if (false == true) {int i = 0;}}");
  894. addDeadCode(newClass, "public void evaluate3(){if (true) {} else {} int i = 0; if (false) {} else {} i++; }");
  895. addDeadCode(newClass, "public void evaluate4(){ for (;false;); int i = false ? 1 : 0; while (true) { return; }}");
  896. addDeadCode(newClass, "public void evaluate5(){ boolean b = !false; b = false && b; b = true && true;"
  897. + " b = true || b; b = b || false; }");
  898. addDeadCode(newClass, "public boolean evaluate6(){ return !false; }");
  899. addDeadCode(newClass, "public boolean evaluate7(){ return !true; }");
  900. newClass.debugWriteFile();
  901. Class<?> cClass = newClass.toClass();
  902. Object o = cClass.newInstance();
  903. java.lang.reflect.Method m = cClass.getMethod("evaluate");
  904. m.invoke(o);
  905. m = cClass.getMethod("evaluate2");
  906. m.invoke(o);
  907. m = cClass.getMethod("evaluate3");
  908. m.invoke(o);
  909. m = cClass.getMethod("evaluate4");
  910. m.invoke(o);
  911. m = cClass.getMethod("evaluate6");
  912. assertTrue((boolean)m.invoke(o));
  913. m = cClass.getMethod("evaluate7");
  914. assertFalse((boolean)m.invoke(o));
  915. m = cClass.getMethod("evaluate5");
  916. m.invoke(o);
  917. }
  918. private void addDeadCode(CtClass cc, String meth) throws Exception {
  919. CtMethod m = CtNewMethod.make(meth, cc);
  920. cc.addMethod(m);
  921. }
  922. public void testAnnArg() throws Exception {
  923. CtClass cc = sloader.get("test4.AnnoArg");
  924. CtMethod m = cc.getDeclaredMethod("foo");
  925. test4.AnnoArg.AnnoArgAt a = (test4.AnnoArg.AnnoArgAt)m.getAnnotations()[0];
  926. assertEquals("test4.AnnoArg$B", a.value().getName());
  927. System.out.println(a.value().getName());
  928. }
  929. public void testDeclaredMethods() throws Exception {
  930. CtClass cc = sloader.get("test4.DeclMethodsList");
  931. CtMethod[] meth = cc.getDeclaredMethods("foo");
  932. assertEquals(2, meth.length);
  933. assertEquals("()V", meth[0].getSignature());
  934. assertEquals("(I)I", meth[1].getSignature());
  935. meth = cc.getDeclaredMethods("bar");
  936. assertEquals(1, meth.length);
  937. assertEquals("()V", meth[0].getSignature());
  938. meth = cc.getDeclaredMethods("baz");
  939. assertEquals(0, meth.length);
  940. }
  941. public void testAnnotationLoader() throws Exception {
  942. CtClass anno = sloader.makeAnnotation("test4.AnnoLoadAnno");
  943. anno.debugWriteFile();
  944. CtClass cc = sloader.get("test4.AnnoLoad");
  945. CtMethod m = cc.getDeclaredMethod("foo");
  946. ClassFile cf = cc.getClassFile();
  947. ConstPool cp = cf.getConstPool();
  948. AnnotationsAttribute attr
  949. = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
  950. Annotation a = new Annotation(anno.getName(), cp);
  951. a.addMemberValue("value", new javassist.bytecode.annotation.StringMemberValue("file/path", cp));
  952. attr.setAnnotation(a);
  953. m.getMethodInfo().addAttribute(attr);
  954. cc.writeFile();
  955. Class<?> rc = ((java.lang.annotation.Annotation)m.getAnnotations()[0]).annotationType();
  956. assertEquals(anno.getName(), rc.getName());
  957. }
  958. }