Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 792
  • Last Modified:

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.
0
a1programmer
Asked:
a1programmer
  • 2
1 Solution
 
CEHJCommented:
You could use a Java app-enabled scripting language (try Groovy) or beanshell
0
 
enachemcCommented:
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now