java 使用反射获取字段值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44395874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:09:14  来源:igfitidea点击:

Get field values using reflection

javareflection

提问by rama

I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

我无法获取字段值。我想要做的是在运行时获取对象。请让我知道我哪里出错了。

Test.class

测试类

import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}

}

}

EX.class

EX.class

public class EX {

private String value;


public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}

}

}

回答by ManoDestra

Something like this...

像这样的东西...

import java.lang.reflect.Field;

public class Test {
    public static void main(String... args) {
        try {
            Foobar foobar = new Foobar("Peter");
            System.out.println("Name: " + foobar.getName());
            Class<?> clazz = Class.forName("com.csa.mdm.Foobar");
            System.out.println("Class: " + clazz);
            Field field = clazz.getDeclaredField("name");
            field.setAccessible(true);
            String value = (String) field.get(foobar);
            System.out.println("Value: " + value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Foobar {
    private final String name;

    public Foobar(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

Or, you can use the newInstancemethod of class to get an instance of your object at runtime. You'll still need to set that instance variable first though, otherwise it won't have any value.

或者,您可以使用newInstance类的方法在运行时获取对象的实例。不过,您仍然需要先设置该实例变量,否则它将没有任何值。

E.g.

例如

Class<?> clazz = Class.forName("com.something.Foobar");
Object object = clazz.newInstance();

Or, where it has two parameters in its constructor, String and int for example...

或者,它的构造函数中有两个参数,例如 String 和 int ......

Class<?> clazz = Class.forName("com.something.Foobar");
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("Meaning Of Life", 42);

Or you can interrogate it for its constructors at runtime using clazz.getConstructors()

或者您可以在运行时使用它的构造函数来询问它 clazz.getConstructors()

NB I deliberately omitted the casting of the object created here to the kind expected, as that would defeat the point of the reflection, as you'd already be aware of the class if you do that, which would negate the need for reflection in the first place.

注意,我故意省略了将此处创建的对象转换为预期类型的​​过程,因为这会破坏反射的重点,因为如果您这样做,您已经知道该类,这将否定反射的需要第一名。

回答by Ady Junior

You need the EX isntance on field.get().

您需要 field.get() 上的 EX 实例。

final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
field.setAccessible(true);
field.get(new EX());

回答by gati sahu

You can create instance from class object and that can be used in field get value.

您可以从类对象创建实例,并且可以在字段获取值中使用。

 Class modelClass = Class.forName("com.gati.stackoverflow.EX");
    final Field field = modelClass.getDeclaredField("value");
    field.setAccessible(true);
    Object modelInstance=modelClass.newInstance();
    field.get(modelInstance);

回答by harshavmb

So, have got the below answer. It is working fine for now. Not sure whether this is the best one to follow.

所以,得到了下面的答案。它现在工作正常。不确定这是否是最好的遵循。

Your Test class :

你的测试课:

public class Test {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
            IllegalArgumentException, IllegalAccessException, InstantiationException {

        Field[] fields = Class.forName("com.logging.EX").newInstance().getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            System.out.println(field.getName() + " : " + field.get(Class.forName("com.logging.EX").newInstance()));
        }

    }
}

I'm extracting all the fields in to an array by invoking the instance of com.logging.EXand then loops through all the fields and extracts the name and the value the field holds. Haven't hardcoded any field name here.

我通过调用 的实例将com.logging.EX所有字段提取到数组中,然后循环遍历所有字段并提取该字段的名称和值。这里没有硬编码任何字段名称。

There are few security caveats with mine as I've accessed the variable with privateaccess modifier but that always exists with reflection. Just a disclaimer!

我的安全警告很少,因为我已经使用private访问修饰符访问了变量,但它始终存在于反射中。只是免责声明!

Hope this helps!

希望这可以帮助!