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
|
/*
* Copyright (c) Brett Randall 2004. All rights reserved.
*
* Created on Jul 20, 2004
*/
package javassist;
import junit.framework.TestCase;
/**
* @author brandall
*/
@SuppressWarnings({"rawtypes","unused"})
public class LoaderTestByRandall extends TestCase {
ClassPool cp;
Loader loader;
public LoaderTestByRandall(String name) {
super(name);
}
public void setUp() {
cp = new ClassPool();
cp.appendSystemPath();
loader = new Loader(cp);
}
public void testLoadGoodClass() throws Exception {
String name = "javassist.LoaderTestByRandall";
cp.get(name);
Class clazz = loader.loadClass(name);
assertEquals("Class not loaded by loader",
loader, clazz.getClassLoader());
}
public void testLoadGoodClassByDelegation() throws Exception {
Class clazz = loader.loadClass("java.lang.String");
}
public void testLoadBadClass() {
try {
Class clazz = loader.loadClass("never.going.to.find.Class");
fail("Expected ClassNotFoundException to be thrown");
} catch (ClassNotFoundException e) {
// expected
}
}
public void testLoadBadClassByDelegation() {
try {
Class clazz = loader.loadClass("java.never.going.to.find.Class");
fail("Expected ClassNotFoundException to be thrown");
} catch (ClassNotFoundException e) {
// expected
}
}
public void testLoadBadCodeModification() throws Exception {
String classname = "javassist.LoaderTestByRandall";
Translator trans = new Translator() {
public void start(ClassPool pool)
throws NotFoundException, CannotCompileException
{
}
public void onLoad(ClassPool pool, String classname)
throws NotFoundException, CannotCompileException
{
String body = new String("this will never compile");
CtClass clazz = pool.get(classname);
CtMethod newMethod = CtNewMethod.make(CtClassType.voidType,
"wontCompileMethod",
new CtClass[] {},
new CtClass[] {},
body,
clazz);
clazz.addMethod(newMethod);
}
};
loader.addTranslator(cp, trans);
try {
Class clazz = loader.loadClass(classname);
fail("Expected loader to throw ClassNotFoundException " +
"caused by CannotCompileException");
} catch (ClassNotFoundException e) {
// expected
System.out.println(e);
assertEquals("ClassNotFoundException was not caused "
+ "by CannotCompileException",
CannotCompileException.class,
e.getCause().getClass());
}
}
}
|