compiling | Dynamic We know that there are eval numbers in many scripting languages, which converts strings to statements and executes them. As in JavaScript
var str = aid.value + ". Style.top = 10;"
the value of an ID for "aid" to be taken out to combine into a string, if the value of aid is "Axman", then
str = "Axman.style.top = 10"
now we want to move the control Axman to the top 10 position:
eval (str);
so this string becomes an expression or the statement begins execution. Such a function is very important for dynamic construction of variables
meaning.
So in Java, what if this functionality is implemented? In fact, we can use dynamic compilation to achieve:
assume that there is a set of methods to implement different functions, and now to invoke the corresponding method based on the method name passed in, if there is no eval function, we
can only do this:
MyClass mc = new MyClass ();
if (str.equals ("M1"))
mc.m1 ();
Else if (str.equals ("M1"))
mc.m2 ();
Else if (str.equals ("M3"))
mc.m3 ();
else if (...)
......... ();
If there are 100 kinds of situations?
If we use the Eval method, we can do this directly:
String str = ......
eval ("MC" +str+ "();");
is not very convenient? The key is how to implement eval ()?
we construct a complete class of strings to be converted: If the method has a return value. Then:
Public Object eval (String str) {
//Generate 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", "Directory", "Temp.java"};
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.