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