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;
}
4
  • 1
    Why do you want to do this? Commented Jul 16, 2014 at 4:12
  • 4
    This can be done with "Reflection". But why? Commented Jul 16, 2014 at 4: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, and it's a pretty unusual request. Commented Jul 16, 2014 at 4: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 Commented Jul 16, 2014 at 4:51

3 Answers 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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

well the code looks okie, will try and update soon. thanks :)
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");

1 Comment

well this works fine for any variable which have a public scope. Any ways thanks :)
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.

1 Comment

The object is already created, so you cant do constructor injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.