posted 21 years ago
hi all
Thanks for poting your reply'w . I just happened to write a simple program and used reflectiion to get what i needed. I'm pasting below what i had written an could be of a lotta use.
import java.io.*;
import java.lang.reflect.*;
public class expression
{
public static void main (String []arg)
{
//String strin="((45 > 21) && (45 < 61)) || ((47 > 25) && (47< 51))";
//Assuming u have a string as follows
String strin="((45 < 21) && (45 < 61)) || ((47 > 25) && (47< 51))";
//Creates a temporary file called Samp and assigns the string value toa boolean
String fileContent="package .net; \n"
+"public class Samp {\n "
+" boolean X = "+strin+";\n "
+" public boolean getValue() "
+" { \n"
+" return X;\n"
+" }\n"
+" }";
String args[] = { "-classpath", ".",
"-sourcepath", ".",
"-d", ".",
//"-verbose",
"Samp.java"};
BufferedWriter wr = null;
try
{
// write the file to the disc
wr = new BufferedWriter(new FileWriter("Samp.java"));
wr.write(fileContent);
wr.close();
//Code for compilation
boolean x = new sun.tools.javac.Main(System.out,"javac").compile(args);
//Use reflection to get the class that has been generated
Class c = Class.forName("Samp");
//Get an object of the class
Object o = c.newInstance();
//Invoke a method on the object
Method m = c.getDeclaredMethod("getValue", null);
String tsReturn=m.invoke(o,null).toString();
System.out.println(m.invoke(o,null));
System.out.println(tsReturn);
boolean returnBool=Boolean.valueOf(tsReturn).booleanValue();
System.out.println(returnBool);
}
catch(Exception e)
{
}
}
}