Update dynamic compilation example

This commit is contained in:
Thibaud Gasser 2018-10-23 23:50:20 +02:00
parent b3a8fb67c9
commit 5b25596359

View File

@ -1,5 +1,7 @@
package fr.gasser.reflection.dynamicload; package fr.gasser.reflection.dynamicload;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -8,8 +10,6 @@ import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Arrays; import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class DynamicLoadDemo { public class DynamicLoadDemo {
@ -25,15 +25,15 @@ public class DynamicLoadDemo {
+ " return \"Hello world!\";" + " return \"Hello world!\";"
+ " }" + " }"
+ " public String doSomethingReflection(String arg) {" + " public String doSomethingReflection(String arg) {"
+ " return \"Hello reflection! \" + \"arg\";" + " return \"Hello reflection! \" + arg;"
+ " }" + " }"
+ "}"; + "}";
/** /**
* Represents the contract for the dynamically loaded class * Represents the contract for the dynamically loaded class
*/ */
public static interface IDynamicLoad { public interface IDynamicLoad {
public String doSomething(); String doSomething();
} }
/** /**
@ -68,8 +68,7 @@ public class DynamicLoadDemo {
// Invoke methods using the reflection API // Invoke methods using the reflection API
Method method = cls.getDeclaredMethod("doSomethingReflection", String.class); Method method = cls.getDeclaredMethod("doSomethingReflection", String.class);
String arg = "argument";
System.out.format("invoking %s.doSomethingReflection()%n", cls.getName()); System.out.format("invoking %s.doSomethingReflection()%n", cls.getName());
System.out.println(method.invoke(instance, arg)); System.out.println(method.invoke(instance, "With an argument"));
} }
} }