public
Created

Example on how to do dynamic variable binding in Java

  • Download Gist
Dynamic.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
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));
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.