Create an object dynamically in java

This question already has an answer here:

  • Create new object using reflection? 2 answers
  • What is reflection and why is it useful? 20 answers

  • 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 ;)

    链接地址: http://www.djcxy.com/p/47624.html

    上一篇: 从字符串执行方法

    下一篇: 在java中动态创建一个对象