我想在Object不使用setter的情况下向变量插入值.怎么可能.
这是一个例子
Class X{
String variableName;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个包含variable name,value to be set和a的功能Object of the Class X.
我试图使用泛型方法将值设置为Object(objectOfClass),其值为i已传递(valueToBeSet)在相应的变量(variableName)中.
Object functionName(String variableName, Object valueToBeSet, Object objectOfClass){
//I want to do the exact same thing as it does when setting the value using the below statement
//objectOfClass.setX(valueToBeSet);
return objectOfClass;
}
Run Code Online (Sandbox Code Playgroud)
如果你确定你真的需要这个,请三思,但无论如何:
import java.lang.reflect.Field;
...
X x = new X();
Field variableName = x.getClass().getDeclaredField("variableName");
// this is for private scope
variableName.setAccessible(true);
variableName.set(x, "some value");
Run Code Online (Sandbox Code Playgroud)
此代码未经过测试.你可以试试这个.
要导入的类
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
Run Code Online (Sandbox Code Playgroud)
方法
public Object functionName(String variableName, Object valueToBeSet, Object objectOfClass) throws IntrospectionException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
//I want to do the exact same thing as it does when setting the value using the below statement
//objectOfClass.setX(valueToBeSet);
Class clazz = objectOfClass.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class); // get bean info
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); // gets all info about all properties of the class.
for (PropertyDescriptor descriptor : props) {
String property = descriptor.getDisplayName();
if(property.equals(variableName)) {
String setter = descriptor.getWriteMethod().getName();
Class parameterType = descriptor.getPropertyType();
Method setterMethod = clazz.getDeclaredMethod(setter, parameterType); //Using Method Reflection
setterMethod.invoke(objectOfClass, valueToBeSet);
}
}
return objectOfClass;
}
Run Code Online (Sandbox Code Playgroud)