Java 使用基于另一个对象的getter的反射调用setter方法的方法
我有两个相关的对象 其中一个是类Java 使用基于另一个对象的getter的反射调用setter方法的方法,java,reflection,getter-setter,Java,Reflection,Getter Setter,我有两个相关的对象 其中一个是类Attribute,另一个类似于名为AddAttributeActionHandler Attribute对象中有很多字段,我需要在AddAttributeActionHandler中设置这些字段。这两个类都有getter和setter,其中一些字段是相等的 基本上,我要做的是从类属性中复制每个可用的getter,并在类AddAttributeActionHandler上调用相应的setter方法 换句话说,我可以执行以下操作(您可以称之为“手动”设置) 问题是有
Attribute
,另一个类似于名为AddAttributeActionHandler
Attribute
对象中有很多字段,我需要在AddAttributeActionHandler
中设置这些字段。这两个类都有getter和setter,其中一些字段是相等的
基本上,我要做的是从类属性中复制每个可用的getter,并在类AddAttributeActionHandler
上调用相应的setter方法
换句话说,我可以执行以下操作(您可以称之为“手动”设置)
问题是有50多个字段。我希望它是全自动的
因此,我找到了以下代码,用于获取对象属性的所有可用公共getter
for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(attributeObj.getClass()).getPropertyDescriptors())
{
if(propertyDescriptor.getReadMethod().toString() != "null")
{
String getterMethodName = propertyDescriptor.getReadMethod().toString();
String getterMethodValue = propertyDescriptor.getReadMethod().invoke(attributeObj).toString());
}
}
上面的代码获取对象中可用的每个getter并打印其值
现在,我需要找出类AddAttributeActionHandler
的对象中是否有相应的setter方法,并在属性
对象中设置从getter获得的属性
可能吗
如果是,请提供任何线索
提前谢谢 您可以从库中使用。不要使用toString()
。使用getName()
和getParameterTypes()
。然后看看并发现你自己。。。
for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(attributeObj.getClass()).getPropertyDescriptors())
{
if(propertyDescriptor.getReadMethod().toString() != "null")
{
String getterMethodName = propertyDescriptor.getReadMethod().toString();
String getterMethodValue = propertyDescriptor.getReadMethod().invoke(attributeObj).toString());
}
}