1. import java.lang.reflect.Method;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class RuntimeWrapper {
  5. private final Map<String, Object> runtimeMap = new HashMap<>();
  6. /**
  7. * Registers a runtime environment value.
  8. * @param key The name of the runtime value.
  9. * @param value The value to register.
  10. */
  11. public void registerRuntimeValue(String key, Object value) {
  12. runtimeMap.put(key, value);
  13. }
  14. /**
  15. * Retrieves a runtime environment value.
  16. * @param key The name of the runtime value.
  17. * @return The value associated with the key, or null if not found.
  18. */
  19. public Object getRuntimeValue(String key) {
  20. return runtimeMap.get(key);
  21. }
  22. /**
  23. * Executes the given code within a controlled environment.
  24. * @param code The code to execute as a string.
  25. * @param args The arguments for the code.
  26. * @return The result of the code execution, or null if an error occurs.
  27. * @throws Exception if an unexpected error occurs during execution.
  28. */
  29. public Object execute(String code, Object[] args) throws Exception {
  30. try {
  31. // Create a new classloader for isolated execution.
  32. ClassLoader classLoader = getClass().getClassLoader(); // Use current classloader
  33. // Dynamically load the code.
  34. Class<?> clazz = classLoader.loadClass("TestClass", true, new ClassLoader.CustomClassLoader()); // CustomClassLoader to avoid dependency issues
  35. // Get the method to execute.
  36. Method method = clazz.getMethod("run", Object[].class);
  37. // Prepare arguments for the method.
  38. Object[] methodArgs = new Object[args.length];
  39. for (int i = 0; i < args.length; i++) {
  40. methodArgs[i] = args[i];
  41. }
  42. // Execute the method.
  43. return method.invoke(null, methodArgs);
  44. } catch (Exception e) {
  45. System.err.println("Error executing code: " + e.getMessage());
  46. throw e;
  47. }
  48. }
  49. // Custom ClassLoader to address class loading issues
  50. class CustomClassLoader extends ClassLoader {
  51. public CustomClassLoader(ClassLoader parent) {
  52. super(parent);
  53. }
  54. @Override
  55. public Class<?> loadClass(String name, boolean qualifiedName, ClassLoader parent) throws ClassNotFoundException {
  56. //This is a placeholder, you can implement custom classloading logic here.
  57. //For basic testing, it can simply return the original class.
  58. return super.loadClass(name, qualifiedName, parent);
  59. }
  60. }
  61. }

Add your comment