简体   繁体   English

Java反射-获取现有对象中的当前字段值

[英]Java Reflection - Get Current Field Value in Existing Object

I have a constructed object of the type below, 我有以下类型的构造对象,

public class Form {
   private String a;
   private String b;
   private Boolean c;

   public String getA() { return a; }
   public void setA (String a) { this.a = a; }
   public String getB() { return b; }
   public void setB (String b) { this.b = b; }
   public Boolean getC() { return c; }
   public void setC (Boolean c) { this.c = c; }
}

I'm using reflection to examine an existing object, eg this Form: ("testA", "testB", False) 我正在使用反射来检查现有对象,例如此Form :( ("testA", "testB", False)

How do I get the current value of a particular field, let's say String b ? 我如何获得特定字段的当前值,比如说String b

// Assume "form" is my current Form object
Field[] formFields = form.getClass().getDeclaredFields();
if (formFields != null) {
   for (Field formField : formFields) { 
       Class type = formField.getType();
       // how do I get the current value in this current object?
   }
}

Use methods of java.lang.reflect.Field : 使用java.lang.reflect.Field方法:

// Necessary to be able to read a private field
formField.setAccessible(true);

// Get the value of the field in the form object
Object fieldValue = formField.get(form);

This is a situation where I am a big proponent of using an external library. 在这种情况下,我强烈支持使用外部库。 Apache Commons BeanUtils is excellent for this purpose and hides a lot of the core java.lang.reflect complexity. Apache Commons BeanUtils在此方面非常出色,并且隐藏了许多核心java.lang.reflect复杂性。 You can find it here: http://commons.apache.org/proper/commons-beanutils/ 您可以在这里找到它: http : //commons.apache.org/proper/commons-beanutils/

Using BeanUtils, the code to satisfy your need would be the following: 使用BeanUtils,满足您需求的代码如下:

Object valueOfB = PropertyUtils.getProperty( formObject, "b" );

Another benefit of using BeanUtils is that it does all of the checking to ensure that you have a proper accessor method for "b" -- getB(). 使用BeanUtils的另一个好处是,它会进行所有检查以确保您具有“ b”的正确访问器方法-getB()。 There are also other utility methods in the BeanUtils library which enable you to handle all sorts of Java bean property manipulation. BeanUtils库中还有其他实用程序方法,使您可以处理各种Java Bean属性操作。

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

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