In javascript you can reference an object's properties using either dot notation, or bracket notation. This can be useful by using a string variable such as:
var myObject = { hello: "world" };
var prop = "hello";
// both will output "world".
console.log( myObject[ prop ] );
console.log( myObject.hello );
Is there a similar syntax in java to access an objects properties using a string variable, similar to javascript's bracket notation?
No, there's not. About the closest thing there is would be using reflection, but that's clunky to say the least. You have to look up the Field
and then get the instance's value for it.
Field property = myInstance.getClass().getDeclaredField("prop");
Object value = property.get(myInstance);
Not what you're looking for, I know, but it's the closest there is unfortunately.
No, there is no such syntax in Java, but there is an API (reflection) that lets you do that, albeit in a less direct way.
1. I don't think there is any syntax like that in java.
2. But i would prefer using the Key-Value
pair, and thats Map
.
3. Reflection API
that can be also used in this case.
There is no similar syntax in java, or any direct way to do this.
java does provide a reflection API that allows you to query an object's properties/interface at runtime using Strings
that represent e.g. an object's properties and methods.
You can also store (key, value) properties in a data structure such as a HashMap
, mapping Strings
to objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With