Reputation: 2735
I would like to be able to dynamically set properties to an existing class (object), during the runtime.
For example, having the interface MyProperty.java
, and other specific properties implementing that interface. Then having an object that can dynamically receive some instance of MyProperty
and automatically have a getter for it.
MyPropery.java [interface representing some Object property]
public interface MyProperty {
String getValue();
}
MyPropertyAge.java [some specific Object property]
public class MyPropertyAge implements MyProperty {
private final String age;
public MyPropertyAge(String age) {
this.age = age;
}
@Override
public String getValue() {
return age;
}
}
MyObject.java [Object that should have a getter for MyProperty dynamically]
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
}
}
So the thing is to have properties added to a class dynamically, based on the set of properties it receives in a constructor. Something similar to dynamic
keyword in C#: Dynamically add properties to a existing object
Is such thing possible in Java, or some hack that would do the same?
Upvotes: 1
Views: 12304
Reputation: 61
There is no such thing as the dynamic
keyword in Java.
However, you could use an internal Map
to store properties. For example:
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);
}
}
Example: Person
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
}
There exist various ways to implement this, but this is probably the most simple way to do it.
Upvotes: 6