Skip to content
Advertisement

Java—how can I dynamically reference an object’s property?

In javascript, I can do this:

JavaScript

Can I do anything close in Java?

JavaScript

Advertisement

Answer

Yes, you can do it by reflection with something along the following lines:

JavaScript

However, if you are not very familiar with Java, this approach should be avoided if at all possible, as it is somewhat dangerous and error prone. For instance, there is no guarantee that the Field you are attempting to set are actually expecting a String. If it is the case that they are not, your program will crash and burn.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement