Is something like the above possible?
No.
With the properties as you have defined them, your only choices are:
If you want dynamic properties, use a Map object; e.g. a HashMap<String, String>.
As to your illustrative example, that won't / can't work because:
- regular object fields cannot be indexed like an array, and
- unlike C++, Python and other languages, Java doesn't support ad-hoc overloading of any of the core language constructs (apart from methods).
Java is not a dynamic language that supports this kind of thing. You need to learn to live with what it can offer you ... or use a different language.
You commented thus:
Reflection is supposed to be bad for performance.
Well yes, but it is relative. Accessing or updating a field reflectively is likely to be 10 to 100 times slower than accessing/updating it using normal Java code. However, if you are only doing this occasionally, the performance overhead may not be relevant. If it does turn out to be an issue, then your options include hand-writing, or generating the code. For example:
public class Foo
{
public String bar;
public String baz;
public void setNamedProperty(String name, String value) {
switch (name) {
case "bar":
bar = value;
break;
case "baz":
baz = value;
break;
default:
throw new IllegalArgumentException("Unknown property name");
}
}
}
For what it is worth, that code is going to be about as time efficient as setting a dynamic property in a language that supports dynamic properties. (And I suspect it will be more space efficient, given that dynamic properties are typically implemented using native coded hash tables.)
without reflectionrestriction?HashMap.