7

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;
}
Dileep
  • 5,362
  • 3
  • 22
  • 38
  • 1
    Why do you want to do this? – Code-Apprentice Jul 16 '14 at 04:12
  • 4
    This can be done with "Reflection". But why? – Thilo Jul 16 '14 at 04:12
  • If we knew what you were doing this for, it is likely that we could suggest a much more elegant solution. Please give us some context. You're essentially asking how to [write Java code on the fly](http://stackoverflow.com/questions/24665848/java-run-a-string-as-normal-code), and it's a pretty unusual request. – aliteralmind Jul 16 '14 at 04:26
  • I am creating a mechanism which creates something like a string pool, for multiple DB tables. SO i need its use. Its pretty much complex to explain in the comments. Hope you guys understand – Dileep Jul 16 '14 at 04:51

3 Answers3

5

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");
p_xr
  • 59
  • 3
5

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;
    }
Coder
  • 6,948
  • 13
  • 56
  • 86
0

There are two ways of setting values in object

1-Constructor Injection -- "Pushing" dependencies into a concrete class through constructor arguments.

2-Setter Injection -- "Pushing" dependencies into a concrete class through public properties. The "Setter" nomenclature is taken from Java where properties are getSomething() and setSomething(value).

As you don't want to use setters ,You can create a parameterised constructor to do so.Parameterized constructors are required to pass parameters on creation of objects.Except it I don't think that there is any other way of doing that without calling setters.

Abhijeet Panwar
  • 1,837
  • 3
  • 26
  • 48