Example on how to do dynamic variable binding in Java
package dynamic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
/**
* Console example application.
*
* For a proof of concept for dynamic assignment.
*/
public class Dynamic {
/**
* The "dynamic" variable map. We add variables in it. They key is the
* variable name and the value is the variable content.
*/
HashMap<String, String> vars = new HashMap<String, String>();
/**
* Main routine to start the dynamic example console app
*/
public static void main(String[] args) throws IOException {
// Creates object of this class and runs it
new Dynamic().run();
}
/**
* The app main method
*
* @throws IOException
* because of the readers may throw an exception sometimes
*/
private void run() throws IOException {
// Make buffered reader, (easy to handle strings with newlines)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Helpful message
System.out.println("To quit type \"quit\" or \"exit\".");
System.out.println("To assign type \"variable name = value\"");
System.out.println("To view the assignment type in the variable name");
// Starting input, empty string
String input = "";
// While the app is not quitting, handle the line and then get next line
while (!input.equals("quit") && !input.equals("exit")) {
handleLine(input);
System.out.print("> ");
input = in.readLine();
}
}
/**
* Method that handles the line
*
* @param input
* the input from console to handle
*/
private void handleLine(final String input) {
// Guard statement if the string is empty or null just jump out
if (input == null || input.length() == 0) {
return;
}
// If input has an assignment, assign it to the vars map
if (input.contains("=")) {
// Cheap way to handle the assignment by splitting the string
// and trimming the splits
String[] split = input.split("=");
String key = split[0].trim(); // Right of = is variable name
String value = split[1].trim(); // Left of = is the value
this.vars.put(key, value);
// output what has been stored
System.out.println("Stored " + value + " in " + key);
}
// If input is a string, assume it's a "variable name" key so output
// the variable
else {
String key = input.trim();
System.out.println(key + ": " + vars.get(key));
}
}
}