1

I was trying to figure out if there is a similar way in java as there is in javascript to get an objects member variable using a string rather than with explicit dot notation.

For Example in javascript I can access an elements member variable by:

someObj["memVarName"] and someObj.memVarName 

So is there any given way without me having to write a specific method to do this?

lennon310
  • 12,503
  • 11
  • 43
  • 61
James Smith
  • 19
  • 1
  • 3
  • possible duplicate of [Java: How can I access a class's field by a name stored in a variable?](http://stackoverflow.com/questions/2127197/java-how-can-i-access-a-classs-field-by-a-name-stored-in-a-variable) – Boann Nov 04 '14 at 14:36

4 Answers4

2

Something like

someObj.getClass().getField("memVarName").get(someObj)

However, generally, in Java, when you are tempted to use reflection, the problem you are trying to solve is probably better solved using a Map or interfaces.

BPS
  • 1,606
  • 20
  • 37
2

Syntatically - no. Java, is not loosely typed like JavaScript and the developer doesn't have as much freedom operating on object fields in the former as he would normally do in the latter.

You could however go into depths of Reflection API and - knowing the name of the getter/setter of particular interest - you might want to take a peek here How to define dynamic setter and getter using reflection?, but as you should probably notice at a first glance - it's not worth the hassle.

Community
  • 1
  • 1
lesz3k
  • 148
  • 9
0

A hashtable object would allow a similar function.

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

Hashtable<String, Integer> numbers
 = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);

To retrieve a number, use the following code:

Integer n = numbers.get("two");
if (n != null) {
  System.out.println("two = " + n);
 }

Taken from http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html

0

You could use BeanUtils (an apache project), while not as neat as a language like JavaScript, it is less painful than using the Reflection API.

Googles Guava library also offers a wrapper around the Reflections API to allow for this sort of "named access"

Failing that you are stuck with the Reflection and Bean APIs in core Java.

Gavin
  • 1,725
  • 21
  • 34