-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodeGenerator.kt
More file actions
57 lines (46 loc) · 2.06 KB
/
CodeGenerator.kt
File metadata and controls
57 lines (46 loc) · 2.06 KB
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
package com.study.proxy.impl
import com.study.proxy.impl.handler.ClassInitHandler
import com.study.proxy.impl.handler.ConstructorHandler
import com.study.proxy.impl.handler.FieldHandler
import com.study.proxy.impl.handler.InstanceMethodHandler
import com.study.proxy.impl.util.ClassNameProvider
import com.study.proxy.impl.util.MethodHandler
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.ClassNode
import java.io.FileOutputStream
import java.lang.reflect.Proxy
class CodeGenerator {
fun generate(specifiedInterface: Class<*>): ByteArray {
if (!specifiedInterface.isInterface) {
val message = "[${specifiedInterface.getCanonicalName()}] is not an interface, please check!"
throw IllegalArgumentException(message)
}
val specifiedInterfaceType = Type.getType(specifiedInterface)
val classReader = ClassReader(specifiedInterfaceType.className)
val classNode = ClassNode()
classReader.accept(classNode, 0)
val classWriter = ClassWriter(ClassWriter.COMPUTE_MAXS or ClassWriter.COMPUTE_FRAMES)
classWriter.visit(
classNode.version,
// TODO: is the flag always correct here?
Opcodes.ACC_PUBLIC or Opcodes.ACC_SUPER or Opcodes.ACC_FINAL,
ClassNameProvider.internalName(),
null,
Type.getInternalName(Proxy::class.java),
arrayOf(specifiedInterfaceType.internalName)
)
val methods = MethodHandler.process(specifiedInterface)
FieldHandler(classWriter, methods).process()
ConstructorHandler(classWriter).process()
InstanceMethodHandler(classWriter, methods).process()
ClassInitHandler(classWriter, methods, specifiedInterface).process()
classWriter.visitEnd()
val ignored = FileOutputStream(ClassNameProvider.SIMPLE_NAME + ".class")
val byteArray = classWriter.toByteArray()
ignored.write(byteArray)
return byteArray
}
}