-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
84 lines (71 loc) · 3.16 KB
/
Main.java
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
package compiler.processor.write;
import compiler.StringJavaObject;
import javax.annotation.processing.Processor;
import javax.tools.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
public class Main {
public static final String CLASS_NAME = "ProcessorTest";
public static final String ANNOTATION_CODE = """
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@interface ProcessorClass {
}
""";
public static void main(String[] args) throws Exception {
String code = """
@ProcessorClass
public interface ProcessorTest {
void print();
void show(String a);
}
""";
// 获取类及实例
compile(ANNOTATION_CODE + code, new WriteProcessor());
Class<?> aClass = loadClass("ProcessorTestImpl");
Object o = aClass.getConstructor().newInstance();
// 执行方法
aClass.getMethod("print").invoke(o);
aClass.getMethod("show", String.class).invoke(o, "a");
// 清除编译结果
Files.delete(Paths.get(CLASS_NAME + ".class"));
Files.delete(Paths.get("ProcessorClass.class"));
Files.delete(Paths.get("ProcessorTestImpl.java"));
Files.delete(Paths.get("ProcessorTestImpl.class"));
}
private static void compile(String code, Processor processor) throws IOException {
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> listener = new DiagnosticCollector<>();
try (StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(listener, Locale.CHINA, StandardCharsets.UTF_8)) {
List<StringJavaObject> compilationUnits = List.of(new StringJavaObject(CLASS_NAME, code));
JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, listener, null, null, compilationUnits);
task.setProcessors(List.of(processor));
task.call();
System.out.println("=== Diagnostics ===");
listener.getDiagnostics().forEach(System.out::println);
}
}
private static Class<?> loadClass(String cls) throws Exception {
return new ClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
String file = name.replace(".", FileSystems.getDefault().getSeparator()) + ".class";
byte[] bytes = Files.readAllBytes(Paths.get(file));
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}.loadClass(cls);
}
}