如果在运行时我引用了 bean 实例和 属性 名称,如何知道 属性 值?

How to know property value if in runtime I have reference to bean instance and property name?

我有以下 bean

class MyBean{
  Date myDate;
  String anotherProperty;
  ...
}

和以下方法:

public static Date getDateField(MyBean instance, String propertyName){
   ...
}

我想像这样调用以下方法:

getDateField(myBeanInstance, "myDate")

我觉得可以实现,但我不知道如何实现 getDateField 方法。

您可以使用反射来访问字段值,例如:

Class  aClass = MyBean.class
Field field = aClass.getField("myDate");
Object value = field.get(myBeanInstance);

你可以使用你传入的两个值来使用reflection获取值。要获得 Field,您必须在 Class 上调用 getDeclaredField(因为它是私有的,否则我们会使用 getField)(可以通过 运行 getClass 在您的实例上。

Field f = instance.getClass().getDeclaredField(propertyName);

因为您没有访问修饰符,所以您只能使用默认访问权限 package-private,因此您必须让外部世界可以访问该字段,这可以通过调用 setAccessible[ 来完成=24=]

f.setAccessible(true);

然后您可以通过在 Field 上调用 get 来获取您的值!

Date d = (Date) f.get(instance);

您应该在 Java Tutorials Website and Wikipedia 上阅读关于 Reflection 的内容,两者都会显着提高您的知识,下次您将能够自己弄明白!

因为您知道 属性 的名称,您可以创建 java.beans.PropertyDescriptor.

的实例
new PropertyDescriptor(propertyName, myBeanInstance.getClass())

或者如果您已经知道 myBeanInstance 的类型是 MyBean 那么

new PropertyDescriptor(propertyName, MyBean.class)

然后您可以通过 getReadMethod() 访问它的 getter Methodinvoke 它在 instance.

所以你的代码看起来像

Object value = new PropertyDescriptor(propertyName, instance.getClass())
                    .getReadMethod()
                    .invoke(instance);