История изменений
Исправление
Legioner,
(текущая версия)
:
var javaCompiler = ToolProvider.getSystemJavaCompiler();
var fileManager = javaCompiler.getStandardFileManager(null, ENGLISH, UTF_8);
var fileSystem = Jimfs.newFileSystem(Configuration.unix());
var evalString = "k1 = \"test\"; k2 = \"tset\";";
Files.writeString(fileSystem.getPath("/Example.java"), "" +
"public class Example implements Runnable {" +
" public String k1, k2;" +
" public void run() {" +
" " + evalString + "" +
" }" +
"}");
var sources = fileManager.getJavaFileObjects(fileSystem.getPath("/Example.java"));
javaCompiler.getTask(null, fileManager, null, null, null, sources).call();
var bytecode = Files.readAllBytes(fileSystem.getPath("/Example.class"));
var classLoader = new ClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.equals("Example")) {
return defineClass(name, bytecode, 0, bytecode.length);
}
return super.findClass(name);
}
};
var exampleClass = classLoader.findClass("Example");
var exampleObj = (Runnable) exampleClass.getConstructor().newInstance();
exampleObj.run();
System.out.println(exampleClass.getField("k1").get(exampleObj));
Требует com.google.jimfs:jimfs:1.1
Исходная версия
Legioner,
:
var javaCompiler = ToolProvider.getSystemJavaCompiler();
var fileManager = javaCompiler.getStandardFileManager(null, ENGLISH, UTF_8);
var fileSystem = Jimfs.newFileSystem(Configuration.unix());
var evalString = "k1 = \"test\"; k2 = \"tset\";";
Files.writeString(fileSystem.getPath("/Example.java"), "" +
"public class Example implements Runnable {" +
" public String k1, k2;" +
" public void run() {" +
" " + evalString + "" +
" }" +
"}");
var sources = fileManager.getJavaFileObjects(fileSystem.getPath("/Example.java"));
javaCompiler.getTask(null, fileManager, null, null, null, sources).call();
var bytecode = Files.readAllBytes(fileSystem.getPath("/Example.class"));
var classLoader = new ClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.equals("Example")) {
return defineClass(name, bytecode, 0, bytecode.length);
}
return super.findClass(name);
}
};
var exampleClass = classLoader.findClass("Example");
var exampleObj = (Runnable) exampleClass.getConstructor().newInstance();
exampleObj.run();
System.out.println(exampleClass.getField("k1").get(exampleObj));