-1

Following is a class:

class Test{
    int x;
}

Now let's say I make an object of the class:

Test testObj = new Test();

Also, I have a String variable, which has the same value as the class variable:

String var = "x";

Now from this object testObj is there a way, that if I supply the name of the variable through the string var, and get the data type of variable x?

Blip
  • 3,061
  • 5
  • 22
  • 50
psychorama
  • 323
  • 5
  • 17
  • 2
    You can through reflection, but maybe there is a better way of doing it. What is the use case? – engineercoding May 03 '15 at 10:06
  • you can use, getClass method, but its can be used on objects, and not on values, – Saurabh Jhunjhunwala May 03 '15 at 10:08
  • Agree with @engineercoding, this looks like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - you're asking about a particular solution, but you are not explaining why you actually want to do this, and probably this particular solution is not the best way to solve the actual problem. – Jesper May 03 '15 at 10:09
  • possible duplicate of [How to determine an object's class (in Java)?](http://stackoverflow.com/questions/541749/how-to-determine-an-objects-class-in-java) – Jens Schauder May 03 '15 at 10:13

3 Answers3

2

Sure. Use Class.getDeclaredField():

Field field = testObj.getClass().getDeclaredField(var);
Class<?> typeOfField = field.getType();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Yes, using reflection:

String type = testObj.getClass().getDeclaredField(var).getType().getName();
M A
  • 71,713
  • 13
  • 134
  • 174
0

Using reflection you might do

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

MyObject objectInstance = new MyObject();

Object value = field.get(objectInstance);

field.set(objetInstance, value);
Axel Amthor
  • 10,980
  • 1
  • 25
  • 44