使用反射设置对象属性 [英] Using reflection to set an object property
问题描述
我按名称获取类,我需要使用相应的数据更新它们,我的问题是如何使用java
我想要添加方法一些虚拟数据。
我不知道类类型我只是获取类名并使用反射来获取他的数据
I getting class by name and i need to update them with respective data and my question is how to do it with java I want to add the method some dummy data . I don't know the class type I just getting the class name and use reflection to get his data
我使用此代码来获取类实例和
I use this code to get the class instance and
Class<?> classHandle = Class.forName(className);
Object myObject = classHandle.newInstance();
// iterate through all the methods declared by the class
for (Method method : classHandle.getMethods()) {
// find all the set methods
if (method.getName().matches("set[A-Z].*")
并知道我找到了我想要用数据更新它的set方法的列表
我该怎么做。
And know that I find the list of the set method I want to update it with data how can I do that .
假设在课堂名称中我得到了人该类有setSalary和setFirstName等
如何用反射设置它们?
assume that In class name I got person and the class have setSalary and setFirstName etc how can I set them with reflection ?
public class Person {
public void setSalery(double salery) {
this.salery = salery;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
}
推荐答案
您也可以直接使用反射将值设置为属性,而不是尝试调用setter。例如:
Instead of trying to call a setter, you could also just directly set the value to the property using reflection. For example:
public static boolean set(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
致电:
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
set(instance, "salary", 15);
set(instance, "firstname", "John");
仅供参考,这里是等效的通用getter :
@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return (V) field.get(object);
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return null;
}
致电:
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
int salary = get(instance, "salary");
String firstname = get(instance, "firstname");
这篇关于使用反射设置对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!