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

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