9

在 javascript 中,您可以使用点表示法或括号表示法来引用对象的属性。这可以通过使用字符串变量来实现,例如:

var myObject = { hello: "world" };
var prop = "hello";

// both will output "world".
console.log( myObject[ prop ] );
console.log( myObject.hello );

java中是否有类似的语法来使用字符串变量访问对象属性,类似于javascript的括号表示法?

4

4 回答 4

4

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.

于 2012-08-04T03:09:00.157 回答
1

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.

于 2012-08-04T03:08:28.033 回答
1

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.

于 2012-08-04T03:08:42.637 回答
1

1.我认为java中没有类似的语法。

2.但我更喜欢使用这Key-Value对,就是这样Map

3. Reflection API在这种情况下也可以使用。

于 2012-08-04T04:38:16.833 回答