1
  1. Suppose I have this class:

    public class Person {
       private String name;
       private int age;
       //setters and getters
       ...
    }   
    
  2. The following code is not correct, but I want something similar.

    String className="Person";
    String att1 = "name";
    String att2 = "age;
    object o = createClassByName(className);
    setValueForAttribute(o,att1,"jack");
    setValueForAttribute(o,att2,21);"
    
Martin M J
  • 830
  • 1
  • 5
  • 12
  • 3
    [Trial: The Reflection API](https://docs.oracle.com/javase/tutorial/reflect/) – Diego May 02 '15 at 22:34
  • If you're using Spring, PropertyAccessorFactory will help you set the properties with minimal effort. – dnault May 02 '15 at 22:40
  • At least add a constructor so that you don't have to use reflection to set the private fields. Setting private fields by hand via reflection is so "wrong" ... – Stephen C May 02 '15 at 23:24

1 Answers1

0

Are you familiar with hashes? I think you could use a HashMap, which is a common Hash implementation built into the Java library:

HashMap<String,Object> person1 = new HashMap<String,Object>();
person1.put("className", "Person");
person1.put("name", "Jack");
person1.put("age", 21);

Everytime you want to change the values, do: person1.put("name", "Jill")

And to get the values, it's person1.get("name")

If you want to take the class into account, you'll have to get the className and manually compare it in your code, to do different things according to the "class" of the object (which in reality is a HashMap, but nevermind).

Small reminder: doing things this way is considered very messy ;)

JoseHdez_2
  • 4,040
  • 6
  • 27
  • 44