简体   繁体   English

如何从Java反射中获取String字段的值?

[英]How to get value of String field from Java reflection?

I have an object that has a String field. 我有一个具有String字段的对象。 I can obtain this field by calling: 我可以通过以下方式获取此字段:

Field field = someObj.getClass().getField("strField");

I sett a Field#set(Object) method, for setting the value of this instance's field, but the respective getter seems to be Field#get(Object) , which is weird because I would have expected it to be Field#get() . 我设置了一个Field#set(Object)方法,用于设置此实例的字段的值,但是各个getter似乎是Field#get(Object) ,这很奇怪,因为我希望它是Field#get()

How do I obtain the value of the instance's strField ? 如何获取实例的strField的值?

if you are using java.lang.reflect.Field , the "setter" is Field.set(Object,Object) and the "getter" is Field.get(Object) . 如果使用java.lang.reflect.Field ,则“ setter”为Field.set(Object,Object) ,而“ getter”为Field.get(Object) in both cases, the first parameter is the instance on which you want to access the field. 这两种情况下,第一个参数都是您要在其上访问字段的实例。

Even without the getter or the setter methods for a property, you can change or get the value using an object reference and Java Reflection. 即使没有属性的getter或setter方法,也可以使用对象引用和Java Reflection来更改或获取值。

import java.lang.reflect.Field;

public class Bean {

    private String strField;

    public static void main(String[] args) throws Exception {
        Bean bean = new Bean();
        Field field = bean.getClass().getDeclaredField("strField");
        field.set(bean, "Hello");
        System.out.println(field.get(bean));
    }

}

Easiest way is to use BeanUtils : 最简单的方法是使用BeanUtils

String s = BeanUtils.getProperty(someObj, "strField");

Note that BeanUtils will attempt to convert your property into string. 请注意,BeanUtils将尝试将您的属性转换为字符串。 You need to have a getter and setter of the property 您需要对属性进行获取和设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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