Java – how to set a value to a class variable without using a setter
•
Java
I want to insert a value into the object variable without using a setter How is that possible?
This is an example
Class X{
String variableName;
// getters and setters
}
Now I have a function, which contains the variable name, the value to be set and the object of class X
I tried to use a generic method to set the value to object (objectofclass) and pass the value I (valuetobeset) in the corresponding variable (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;
}
Solution
This code has not been tested You can try this
Class to import
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;
method
public Object functionName(String variableName,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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
