How to set values to a class variables without using setters
generics, java
Solution
This code is not tested. You can try this.
Classes 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 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;
}
Problem
I want to insert a value to an `Object` variable without using the setters. How can if be 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 an `Object of the Class X`. I am trying to use a generic method to set the value to the Object(objectOfClass) with the value i have passed(`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; } ```