动态地向类添加属性

时间:2017-03-04 16:54:38

标签: java c#

我希望能够在运行时期间动态地将属性设置为现有的类(对象)。

例如,使用接口MyProperty.java以及实现该接口的其他特定属性。然后让一个对象可以动态接收MyProperty的某个实例,并自动为其设置 getter

MyPropery.java [表示某些Object属性的接口]

public interface MyProperty {
    String getValue();
}

MyPropertyAge.java [某些特定的对象属性]

public class MyPropertyAge implements MyProperty {

    private final String age;

    public MyPropertyAge(String age) {
        this.age = age;
    }

    @Override
    public String getValue() {
        return age;
    }
}

MyObject.java [动态应具有MyProperty getter的对象]

public class MyObject {

    public MyObject(Set<MyProperty> properties) {
        // receive list of properties,
        // and have getters for them
    }

    // For example, if I passed in a Set with 1 instance of "MyPropertyAge", I want to have this

    public MyPropertyAge getMyPropertyAge() {
        // implementation
    }

}

因此,根据它在构造函数中接收的属性集,将属性添加到类动态中。类似于C#中dynamic个关键字的内容:Dynamically add properties to a existing object

在Java中这样的事情是可能的,还是会有同样的黑客攻击?

1 个答案:

答案 0 :(得分:1)

Java中没有dynamic关键字。

但是,您可以使用内部Map来存储属性。例如:

<强> MyObject.java

public class MyObject {
    private HashMap<String, Object> properties;

    //Create object with properties
    public MyObject(HashMap<String, Object> properties) {
        this.properties = properties;
    }

    //Set properties
    public Object setProperty(String key, Object value) {
        return this.properties.put(key, value); //Returns old value if existing
    }

    //Get properties
    public Object getProperty(String key) {
        return this.properties.getOrDefault(key, null);
    }
}

示例:人

public static void main(String[] args) {
    //Create properties
    HashMap<String, Object> properties = new HashMap<>();

    //Add name and age
    properties.put("name", "John Doe");
    properties.put("age", 25);

    //Create person
    MyObject person = new MyObject(properties);

    //Get properties
    System.out.println(person.getProperty("age")); //Result: 25
    System.out.println(person.getProperty("name")); //Result: John Doe
}

有各种方法可以实现这一点,但这可能是最简单的方法。

相关问题