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?