加载一个外部class到jvm中
Arthas可以通过redefine和retransform命令重新加载类, 那么如何加载一个外部class到jvm中呢?
考虑通过ClassLoader实例直接加载编译后的class文件字节码实现。
java代码
java
public class Person {
String name;
Integer age;
// 省略getter/setter
}
1
2
3
4
5
6
2
3
4
5
6
加载过程
使用ArthasClassloader加载class文件字节码到ClassLoader中
bash
# 内存编译java为class文件
[arthas@16936]$ mc /tmp/Person.java -d /tmp
Memory compiler output:
C:\tmp\Person.class
# 借助vmtool获得ArthasClassloader实例加载类
[arthas@16936]$ vmtool -a getInstances --className com.taobao.arthas.agent.ArthasClassloader --express '#path=@java.nio.file.Paths@get(new java.net.URI("file:///C:/tmp/Person.class")),#bytes=@java.nio.file.Files@readAllBytes(#path),instances[0].defineClass("Person", #bytes, 0, #bytes.length)'
@Class[
ANNOTATION=@Integer[8192],
ENUM=@Integer[16384],
SYNTHETIC=@Integer[4096],
cachedConstructor=null,
newInstanceCallerCache=null,
name=null,
allPermDomain=@ProtectionDomain[ProtectionDomain null
null
<no principals>
java.security.Permissions@65f9cc2 (
("java.security.AllPermission" "<all permissions>" "<all actions>")
)
],
useCaches=@Boolean[true],
reflectionData=null,
classRedefinedCount=@Integer[0],
genericInfo=null,
serialVersionUID=@Long[3206093459760846163],
serialPersistentFields=@ObjectStreamField[][isEmpty=true;size=0],
reflectionFactory=@ReflectionFactory[sun.reflect.ReflectionFactory@9fe6d14],
initted=@Boolean[true],
enumConstants=null,
enumConstantDirectory=null,
annotationData=null,
annotationType=null,
classValueMap=null,
]
[arthas@16936]$ sc Person
Person
Affect(row-cnt:1) cost in 4 ms.
# 搜索类发现已经加载
[arthas@16936]$ sc Person -d
class-info Person
code-source
name Person
isInterface false
isAnnotation false
isEnum false
isAnonymousClass false
isArray false
isLocalClass false
isMemberClass false
isPrimitive false
isSynthetic false
simple-name Person
modifier public
annotation
interfaces
super-class +-java.lang.Object
class-loader +-com.taobao.arthas.agent.ArthasClassloader@26d26e26
+-sun.misc.Launcher$ExtClassLoader@4554617c
classLoaderHash 26d26e26
Affect(row-cnt:1) cost in 5 ms.
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
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
较为复杂的场景可参考