Reputation: 267049
Say I have the following class:
class Foo
{
public String bar;
public String baz;
}
And I have the following code, in another class:
Foo foo = new Foo();
String[] properties = {"bar", "baz"};
String[] values = {"barValue", "bazValue"};
Is it possible to iterate over the properties
array and use that to set the values of Foo
? E.g something like:
for (int i = 0; i < properties.length; i++)
{
foo[ properties[i] ] = values[i];
}
Is something like the above possible?
Upvotes: 3
Views: 3259
Reputation: 7282
You can use Introspection
, and it is much better a way when you face Java Beans.
Cons are:
PropertyDescriptor
s.Apache Commons BeanUtils
or Spring BeanWrapper API
.For more information look at java.beans.Introspector
javadocs.
By the way as far as I know Interospection is built upon reflection, so it uses reflection itself.
Upvotes: 1
Reputation: 718708
Is something like the above possible?
No.
With the properties as you have defined them, your only choices are:
writing or generating Java code (or bytecodes) to refer to the fields a foo.bar
or foo.baz
, or
use reflection.
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:
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.)
Upvotes: 6