Dynamic evaluation

Java experts,

Is it possible to do dynamic evaluation in Java?

public class test
{
    public static String username;    

    public static void set(String name, String value)
    {
        eval(name + '=' + value);
    }

}



If I called:
      test.set("username","some_name");

the value "some_name" would get placed in the username String.
LVL 7
a1programmerAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
enachemcConnect With a Mentor Commented:
You can do that through reflection (the java.lang.Reflect package). You can dinamicaly obtain a reference to a field or method. You can assign to the field references or invoke the methods. If you want to set field values (you can use the setters) to instances of some, you would first require the instance.

Example of setting an instance's field value:

public static void set(Object instance, String name, String value)
    {
       Field f = instance.getClass().getField(name);
       //the type of your field should be String (if it's another type, you should convert from String to the required type)
       f.set(instance, value);
    }

0
 
CEHJCommented:
You could use a Java app-enabled scripting language (try Groovy) or beanshell
0
 
a1programmerAuthor Commented:
That's exactly what I was looking for.  

Thanks!
0
 
a1programmerAuthor Commented:
CEHJ,
   Thank you as well for recommending those scripting language.   I had never heard of either, but will keep them at hand for the future.
0
All Courses

From novice to tech pro — start learning today.