Vis*_*tap 7 java reflection setter
我们可以使用属性名称找到setter方法名称吗?
我有一个动态生成的 map<propertyName,propertyValue>
通过使用map中的键(这是propertyName),我需要为object调用适当的setter方法并传递map中的值(即propertyValue).
class A {
String name;
String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
Run Code Online (Sandbox Code Playgroud)
我的地图包含两个项目:
map<"name","jack">
map<"company","inteld">
Run Code Online (Sandbox Code Playgroud)
现在我正在迭代地图,当我从地图继续处理每个项目时,基于密钥(名称或公司),我需要调用类A的适当的setter方法,例如,对于第一项,我将名称作为键,因此需要调用新的A ().setName.
ig0*_*774 17
尽管使用反射可以做到这一点,但使用commons-beanutils可能会更好.您可以轻松地使用这样的setSimpleProperty()方法:
PropertyUtils.setSimpleProperty(a, entry.getKey(), entry.getValue());
Run Code Online (Sandbox Code Playgroud)
假设a是类型A.
Ala*_*ger 13
如果你使用Spring,那么你可能想要使用它BeanWrapper.(如果没有,您可以考虑使用它.)
Map map = new HashMap();
map.put("name","jack");
map.put("company","inteld");
BeanWrapper wrapper = new BeanWrapperImpl(A.class);
wrapper.setPropertyValues(map);
A instance = wrapper.getWrappedInstance();
Run Code Online (Sandbox Code Playgroud)
这比直接使用反射更容易,因为Spring会为您执行常见的类型转换.(它还将尊重Java属性编辑器,以便您可以为它不能处理的那些注册自定义类型转换器.)
Reflection API是你所需要的。假设您知道属性名称并且您有一个a类型为的对象A:
String propertyName = "name";
String methodName = "set" + StringUtils.capitalize(propertyName);
a.getClass().getMethod(methodName, newObject.getClass()).invoke(a, newObject);
Run Code Online (Sandbox Code Playgroud)
当然,你会被要求处理一些异常。
小智 5
使用Map放置字段名称及其Setter方法名称,或使用字符串连接来"设置"第一个字母大写的propertyName似乎是一个非常弱的方法来调用Setter方法.
您知道类名称并且可以遍历其属性并获取每个Property的Setter/GetterMethod名称的方案可以像下面的代码片段一样解决.
你可以从java.beans获得Introspector/Property Descriptor.*;
try {
Animal animal = new Animal();
BeanInfo beaninfo = Introspector.getBeanInfo(Animal.class);
PropertyDescriptor pds[] = beaninfo.getPropertyDescriptors();
Method setterMethod=null;
for(PropertyDescriptor pd : pds) {
setterMethod = pd.getWriteMethod(); // For Setter Method
/*
You can get Various property of Classes you want.
*/
System.out.println(pd.getName().toString()+ "--> "+pd.getPropertyType().toString()+"--Setter Method:->"+pd.getWriteMethod().toString());
if(setterMethod == null) continue;
else
setterMethod.invoke(animal, "<value>");
}
}catch(Exception e) {e.printStackTrace();}
Run Code Online (Sandbox Code Playgroud)
小智 -1
我认为您可以通过反射来做到这一点,一个更简单的解决方案是对键进行字符串比较并调用适当的方法:
String key = entry.getKey();
if ("name".equalsIgnoreCase(key))
//key
else
// company
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17286 次 |
| 最近记录: |