-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloWorldTranslator.java
More file actions
37 lines (31 loc) · 1.36 KB
/
HelloWorldTranslator.java
File metadata and controls
37 lines (31 loc) · 1.36 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
import java.io.IOException;
import java.lang.classfile.ClassFile;
import java.lang.classfile.ClassModel;
import java.lang.classfile.instruction.ConstantInstruction.LoadConstantInstruction;
import java.lang.constant.ClassDesc;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import static java.lang.classfile.ClassFile.ConstantPoolSharingOption;
import static java.lang.classfile.ClassTransform.transformingMethodBodies;
public class HelloWorldTranslator {
public static void main(String[] args) throws IOException {
if (args.length != 2) throw new RuntimeException("Expected input and translation.");
var input = Path.of(args[0]);
var translation = args[1];
var cf = ClassFile.of();
var classModel = cf.parse(input);
byte[] newBytes = cf
.withOptions(ConstantPoolSharingOption.NEW_POOL)
.transformClass(classModel, transformingMethodBodies(
(codeBuilder, codeElement) -> {
if (codeElement instanceof LoadConstantInstruction ldc &&
ldc.constantValue().equals("Hello World")) {
codeBuilder.ldc(translation);
} else {
codeBuilder.with(codeElement);
}
}));
Files.write(input, newBytes);
}
}