Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - let user write own code, then compile it, then use it within same runtime

I need to perform following steps:

  1. Let user write own code - no problem, it's just one interface to implement and I save a file
  2. Compile it - no problem, I used ToolProvider.getSystemJavaCompiler() and created .class file
  3. Let user use this new code - here I am stuck. I have .class file and now what? I need somehow add it in my project and I don't know how.

Thanks for help!

like image 544
Xorty Avatar asked Apr 02 '11 14:04

Xorty


People also ask

Does Java compile during runtime?

In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the javac compiler.

What is runtime polymorphism in Java?

Runtime Polymorphism in Java Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass.

What happens internally if we are compiling and running a Java program?

java' file is passed through the compiler, which then encodes the source code into a machine-independent encoding, known as Bytecode. The content of each class contained in the source file is stored in a separate '.

How do you create a dynamic variable in Java?

There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.


1 Answers

Use a URLClassLoader to load the classes. Then you can use reflection to instantiate and manipulate them.

like image 150
Bozho Avatar answered Sep 19 '22 01:09

Bozho