简体   繁体   中英

How do I get the type of an object's variable if I know the name of the variable in java?

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?

Sure. Use Class.getDeclaredField() :

Field field = testObj.getClass().getDeclaredField(var);
Class<?> typeOfField = field.getType();

是的,使用反射:

String type = testObj.getClass().getDeclaredField(var).getType().getName();

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM