Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Bracket Notation?

Tags:

java

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?

like image 720
Lee Owen Avatar asked Aug 04 '12 03:08

Lee Owen


4 Answers

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.

like image 84
Tyler Treat Avatar answered Oct 29 '22 11:10

Tyler Treat


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.

like image 24
Sergey Kalinichenko Avatar answered Oct 29 '22 11:10

Sergey Kalinichenko


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.

like image 42
Kumar Vivek Mitra Avatar answered Oct 29 '22 12:10

Kumar Vivek Mitra


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.

like image 36
pb2q Avatar answered Oct 29 '22 12:10

pb2q