For real Java code, this is possible using the JavaCompiler interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.

The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.

Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.

Answer from Michael Borgwardt on Stack Overflow
🌐
Medium
medium.com › @Mark.io › running-arbitrary-java-code-on-the-fly-d5003ebd46a8
Running Arbitrary Java Code On The Fly | by Murat Kilic | Medium
September 13, 2019 - We examine how we can use java reflection to execute any provided java bytecode and consume and produce JSON during the process
Discussions

dynamic - How could I call Java code dynamically? - Stack Overflow
How could I write Java code that is executed like javascript code used together with the eval function? What I would like to achieve would be something like this: System.execute ("String str = \"... More on stackoverflow.com
🌐 stackoverflow.com
February 25, 2009
[Java] Dynamic Code Execution
into the textbox, is there a way the java program can execute this code, that is, process it, and print teh result??? More on neowin.net
🌐 neowin.net
7
May 19, 2004
sockets - "Dynamically" executing code in Java - Stack Overflow
I'm looking to execute predefined Java code (hence the quotation marks) when a certain message arrives from a socket. What is the best way of doing this? I thought about parsing the message and then More on stackoverflow.com
🌐 stackoverflow.com
difference between dynamic and static type checking
The difference between static and dynamic type checking is when the type check occurs. In a static type checker, the type checking occurs in the static context - normally compile time. With dynamic type checking, the type check occurs in the dynamic context, aka, at runtime. It should not be confused with strong and weak (or untyped) typing, which is the property of whether or not a value can be coerced into other types, but this confusion is quite common. Many languages support some form of both static and dynamic type checking. For example, in languages like C++, Java, C#, a downcast performs a dynamic type check (correctly named dynamic_cast<> in C++). There is a static type check that the type you are casting from is indeed an ancestor of the type you are casting to, but as to which descendant the value really is, this information is not available until runtime. In Java and C#, every type is a descendant of Object, and thus, any time you cast from Object to something else, a dynamic type check occurs. In early versions of both languages, it was used widely, but the introduction of generics into both languages reduced the need for dynamic type checking, although the need is still very much there in some cases. Clearly, downcasting is useful in practice. This should partly answer your question as to why not statically type check everything. There are some languages which don't have a downcast, such as OCaml, in which you must take a different approach to solve problems where you would otherwise use a downcast. A language which is usually dynamically checked can also have some form of static checking, and in some cases, we call it gradual typing, where it is possible to add more complete type information over time to provide more information to the static context and enable better optimizations. Gradual typing can potentially achieve the same as static typing if there is enough type information present. In general, a need for dynamic type checking arises from the fact that you often wish to have heterogeneous collections of values, and statically typing heterogeneous collections is both not very useful in practice, and can lead to an explosion in code size because you essentially need a type dedicated to each individual collection. [1, "a", true, 'x'] is a different type to ["a", true, 'x', 1], and so forth. More on reddit.com
🌐 r/ProgrammingLanguages
68
17
January 11, 2023
🌐
Datacadamia
datacadamia.com › lang › java › dynamic
Java - Dynamic Java code execution (at runtime)
August 30, 2024 - How to create, compile and run Java code at runtime making it a dynamic, scripting language. The below section is showing parts of the whole script highlighting all the steps needed to create an ...
🌐
GitHub
github.com › raulgomis › dynamic-java-compiler
GitHub - raulgomis/dynamic-java-compiler: Dynamic Java Compiler - Compile Java Code Snippets on demand from text sources · GitHub
Dynamic-java-compiler is a library that allows users to dynamically compile and execute any java source code. Writing dynamically executed Java applications require some boilerplate code: working with classloaders, compilation error handling, etc.
Starred by 18 users
Forked by 7 users
Languages   Java
🌐
JRebel
jrebel.com › blog › runtime-java-code-generation-guide
How to Make Java More Dynamic with Runtime Java Code Generation | JRebel
In order to execute bytecode, it is translated into native machine code at runtime by a JVM’s just-in-time compiler. So much for Java 101.
🌐
Java2s
java2s.com › Tutorials › Java › Java_Utilities › How_to_compile_Java_source_code_and_run_it_dynamically.htm
How to compile Java source code and run it dynamically
File("generated/Hello.java"); FileWriter writer = new FileWriter(sourceFile); writer.write("public class Hello{ \n" + " public void doit() { \n" + " System.out.println(\"Hello world\") ;\n" + " }\n" + "}"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager( null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays .asList(new
Find elsewhere
🌐
InfoWorld
infoworld.com › home › software development › development approaches › design patterns
Add dynamic Java code to your application | InfoWorld
December 6, 2006 - Executing the above statement has the same effect as running javac from the command line with the same arguments. It compiles the source file dynacode/sample/PostmanImpl.java using the specified classpath bin and outputs its class file to the destination directory /temp/dynacode_classes. An integer returns as the error code.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Dynamic Java Code Injection - Java Code Geeks
October 19, 2015 - In this post we're going to look at how to dynamically load Java code into a running jvm. The code might be completely new or we might want to change the
🌐
Baeldung
baeldung.com › home › java › core java › compiling and executing code from a string in java
Compiling and Executing Code From a String in Java | Baeldung
May 23, 2025 - In this tutorial, we’ll learn how to turn a String containing Java source code into a compiled class and execute it. There are many potential applications for compiling code at runtime: Generated code – dynamic code from information that’s not available pre-runtime or that changes often
🌐
Vanillajava
blog.vanillajava.blog › 2024 › 11 › advanced-applications-of-dynamic-code.html
Advanced Applications of Dynamic Code in Java
November 24, 2024 - By generating code dynamically, you can build data stores from interfaces that are either row-based or column-based, stored in the heap or direct memory. This approach reduces the number of objects created, improving cache locality and reducing ...
🌐
Medium
medium.com › @Mark.io › java-dynamic-code-executing-grpc-server-bc7f2510422d
Java Dynamic Code Executing gRPC Server | by Murat Kilic | Medium
September 18, 2019 - ExecutionRequest contains method name in the form of {package Name}.{classname}:{method_name}. For example if the code I would like to execute dynamically has a package of ‘io.mark.java_examples.Executables’ , class name is ‘RunThisCode’, and I’m targeting ‘addPerson’ method, my gRPC client will send method as “io.mark.java_examples.Executables.RunThisCode:addPerson”
🌐
CodingTechRoom
codingtechroom.com › question › run-code-from-string-in-java
How to Execute Code from a String in Java? - CodingTechRoom
However, we can achieve similar functionality using the Java Compiler API or third-party libraries like Janino. ... import javax.tools.*; import java.io.*; public class StringExecution { public static void main(String[] args) throws Exception ...
🌐
Quora
quora.com › How-do-I-generate-a-dynamic-Java-class-and-execute-it
How to generate a dynamic Java class, and execute it - Quora
Answer (1 of 2): You have to create a class file and a classloader that you can instruct to load that class. Whether you use a bytecode generated class or as Muhammed’s answer describes, you compile a file, you have to store that result and feed it to a classloader. Though there are more option...
🌐
Broadcom
ftpdocs.broadcom.com › cadocs › 0 › CA DevTest Solutions 8 0-ENU › Bookshelf_Files › HTML › Doc_Library › 2148763.html
Dynamic Java Execution
The Dynamic Java Execution step lets you instantiate and manipulate a Java object. All Java classes on the DevTest classpath are available, including the classes in the JRE classpath. Any user classes can be placed on the classpath by copying them into the hotDeploy directory.
🌐
Hashnode
techthoughtsexplorer.hashnode.dev › a-comprehensive-guide-to-reflection-in-java-for-developers
Java Reflection: Unlock Dynamic Code Execution
April 23, 2023 - Reflection is a powerful feature in Java that allows developers to examine and modify the behavior of applications during runtime. With reflection, you can inspect classes, interfaces, fields, and methods to retrieve metadata, create instances, invoke methods, and more, all dynamically. Reflection is particularly useful when dealing with code whose structure is unknown at compile-time, enabling flexible and extensible software designs.
🌐
Neowin
neowin.net › technical help & support › programming (c#, c++, java, vb, .net etc.)
[Java] Dynamic Code Execution - Programming (C#, C++, JAVA, VB, .NET etc.) - Neowin
May 19, 2004 - is it possible to dynamically execute code in java without writing an interpretter what i mean is, say for example, you have a window, with a textbox and a button you type int i = 1; i++; System.out.println(i); into the textbox, is there a way the java program can execute this code, that is, proc...
🌐
Coderanch
coderanch.com › t › 378904 › java › Dynamically-compile-execute-java-code
Dynamically compile and execute java code from servlet (Java in General forum at Coderanch)
January 17, 2006 - Using java servlets backed by a tomcat server container build a java web application that given a peice of java code example it should in some way invoke the java compiler and compile the peice of java code reporting any compilation errors.and if compilation is successufull it should display ...
Top answer
1 of 2
2

You can do it in a lot of ways. As people said, you can implement using a lot of desing patterns like Builder.

But here is a simple way to implement your client:

public class DateClient {

    public static void main(String[] args) throws IOException {
        String serverAddress = "ipAdress";
        Socket s = new Socket(serverAddress, 9090); // use the right port
        BufferedReader input
                = new BufferedReader(new InputStreamReader(s.getInputStream()));
        char answer = input.readLine().charAt(0);
        switch (answer) {
            case 'a':
                //do something for a
                break;
            case 'b':
                //do something for b
                break;
            case 'c':
                //do something for c
                break;
            default:
                System.out.println("No valid entry");
        }
        System.exit(0);
    }
}

It needs verification while reading the package from server, or it may throw exceptions.

2 of 2
1

Its not really "dynamically". You mean to execute a command on a given request from the socket?

Rule #1 of building services: Sanitize all input.

For this reason I would avoid any kind of methodology that uses Reflection to obtain method names and execute them that way.

Essentially you are looking for a bit of logic to determine what to do with the input request.

This could be done a number of ways.

  1. Using a switch case on a String name.
  2. Using a HashMap to map the String name to a generic interface (void run( Object input ))
  3. Using an event dispatcher mechanism to alert listeners of input request.

How you decide to implement this is up to you and really depends on your goals.

What you determine to be a "message" from the socket involves formatting. I am assuming that you are formatting the data so the receiver knows a message of X bytes is coming so it can be buffered and processed only when the entire message has been received.

Formatting of data on the socket is beyond the scope of this question. There are lot of resources for designing and building RPC services. May google be with you.