0

Let's say I have Java class:

public class Animal
{
    public String dog = "Rex";
}

In another class I am doing like this:

 Animal mAnimal = new Animal();
 String attributeCaller = "dog";  

PROBLEM: how to call mAnimal attribute "dog" by using String "attributeCaller" value in Java? I mean to do something like this:

 String dogName = mAnimal.attributeCaller;

which simply should be equal to (convenient way of calling attributes in Java):

 String dogName = mAnimal.dog;
user2999943
  • 2,419
  • 3
  • 22
  • 34

3 Answers3

2

You can do it using Java Reflection API: http://docs.oracle.com/javase/tutorial/reflect/. However, I would not recommend using Reflection unless it is really necessary.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
1

You can use java reflection API to inspect the content of any object and achieve that. Here is an example:

String attributeCaller = "dog";
Animal mAnimal = new Animal();
Class<?> c = mAnimal.getClass();

Field f = c.getDeclaredField(attributeCaller);
f.setAccessible(true);

String dogName = (String) f.get(mAnimal); 

Please notice that this doesn't work for superclass fields, to get superclass fields you have to iterate through c.getSuperclass() to find the field

Cirou
  • 1,420
  • 12
  • 18
0

Those seem to be two different classes so that idea will not work.
You have one class called Animal which has a String attribute called dog. Now in another class where you have created an Object of type Animal,in this case that object is called mAnimal,you have to refer to its attribute by the object name,so the variable dogName can be assigned the value of the object like:
String dogName=mAnimal.dog;
or perhaps you want to set that object's attribute like:
mAnimal.dog = "Snoopy"; .
It seems you may understand how Classes and Objects work, I would recommend watching the Lynda.com videos on Java for Beginners or getting the Java How To Program by the Deitel brothers.
If that was helpful consider giving it a point up

Manny265
  • 1,709
  • 4
  • 23
  • 42