We know that there is an EVAL in many script languages, which can convert the string into a prefiguration and execute. Such as in JavaScript
Var str = aid.value ".style.top = 10;"
Take a value of the control of an ID "AID" to merge into a string, if the value of the AXMAN is "Axman", then
Str = "axman.style.top = 10"
Now let's let control Axman move to the top of 10:
EVAL (STR);
This way this string becomes an expression or statement to start execution. Such functions are very important for dynamic constructive variables.
significance.
So in Java, if this feature is implemented? In fact, we can use dynamic compilation:
Suppose there is a set of methods to achieve different functions, now call the corresponding method according to the method name passed, if there is no evAl function, we
Can only do this:
Myclass mc = new myclass ();
IF (Str.Equals)))
mc.m1 ();
ELSE IF (Str.Equals)))
Mc.m2 ();
Else IF (Str.Equals)))
mc.m3 ();
Else IF (.......)
......... ();
If there is a hundred cases?
If we use the Eval method to be just like this:
String str = ...........
EVAL ("MC" STR "();");
Is it very convenient? How is the key to achieve evAl ()?
We construct a complete class to convert the string to be converted: If the method is to return value.
Public Object Eval (String Str) {
/ / Generate a Java file
String s = "Class Temp {";
S = "Object RT () {"
S = "Myclass MC = New Myclass ();"
S = "RETURN MC." Str "();"
S = "}"
S = "}";
FILE F = New File ("Temp.java");
PrintWriter PW = New PrintWriter (New FileWriter (f));
PW.Println (s);
PW.Close ();
// Dynamic compilation
com.sun.tools.javac.main javac = new com.sun.tools.javac.main ();
String [] cpargs = new string [] {"-d", "location directory", "temp.java"}
Int status = javac.compile (cpargs);
IF (status! = 0) {
System.out.println ("No successful compilation source file!");
Return NULL;
}
// call the TEMP RT method to return the result:
MyclassLoader MC = New MyclassLoader ();
Class Clasz = Mc.LoadClass ("Test.class", True;
Method RT = Clasz.getMethod ("RT", new class [] {string []. Class});
Return RT.Invoke (NULL, New Object [] {new string [0]});
// If the method does not return, it is directly called}}
We can write a number of overloaded EVALs, have returned values and no return values. And you can pass parameters.
This way we can use strings to convert to Java statements.
This article is just an example, indicating a dynamic compilation, better implementation, please ask your friends yourself.