Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set values to a class variables without using setters

Tags:

java

generics

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;
}
like image 999
Dileep Avatar asked Jul 16 '14 04:07

Dileep


2 Answers

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;
    }
like image 89
Shiju K Babu Avatar answered Sep 20 '22 22:09

Shiju K Babu


If you are sure that you really need this, please, think twice, but anyway:

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");
like image 32
p_xr Avatar answered Sep 21 '22 22:09

p_xr