Java Bracket Notation?

In javascript, you can reference the properties of an object using either dot notation or a bracket. This can be useful with 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 object properties using a string variable similar to javascript notation?

+6
source share
4 answers

No no. About the next thing will be the use of reflection, but this is inconvenient to say. You must find Field , and then get the instance value for it.

 Field property = myInstance.getClass().getDeclaredField("prop"); Object value = property.get(myInstance); 

Not what you are looking for, I know, but this is the closest, unfortunately.

+4
source

No, there is no such syntax in Java, but there is an API ( reflection ) that allows you to do this, although to a lesser extent a direct path.

+1
source

There is no similar syntax in java or any direct way to do this.

java provides a reflection API that allows you to query object properties / interface at runtime using Strings , which represent, for example. object properties and methods.

You can also save (key, value) properties in the data structure, such as HashMap , matching Strings with objects.

+1
source

1. I do not think java has this syntax.

2. But I would prefer to use a pair of Key-Value and thats Map .

3. Reflection API , which can also be used in this case.

+1
source

Source: https://habr.com/ru/post/922100/


All Articles