Instead of trying to call a setter, you could also just directly set the value to the property using reflection. For example:

public static boolean set(Object object, String fieldName, Object fieldValue) {
    Class<?> clazz = object.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(object, fieldValue);
            return true;
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return false;
}

Call:

Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
set(instance, "salary", 15);
set(instance, "firstname", "John");

FYI, here is the equivalent generic getter:

@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
    Class<?> clazz = object.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return (V) field.get(object);
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return null;
}

Call:

Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
int salary = get(instance, "salary");
String firstname = get(instance, "firstname");
Answer from sp00m on Stack Overflow
Top answer
1 of 4
89

Instead of trying to call a setter, you could also just directly set the value to the property using reflection. For example:

public static boolean set(Object object, String fieldName, Object fieldValue) {
    Class<?> clazz = object.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(object, fieldValue);
            return true;
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return false;
}

Call:

Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
set(instance, "salary", 15);
set(instance, "firstname", "John");

FYI, here is the equivalent generic getter:

@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
    Class<?> clazz = object.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return (V) field.get(object);
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return null;
}

Call:

Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
int salary = get(instance, "salary");
String firstname = get(instance, "firstname");
2 of 4
3

To update the first name

  • First find the field you want to update
  • Then find the mutator (which accepts an argument of the field's type)
  • Finally execute the mutator on the object with the new value:
Field field=classHandle.getDeclaredField("firstName");
Method setter=classHandle.getMethod("setFirstName", field.getType());
setter.invoke(myObject, "new value for first name");
🌐
Oracle
docs.oracle.com › javase › tutorial › reflect › member › fieldValues.html
Getting and Setting Field Values (The Java™ Tutorials > The Reflection API > Members)
See Java Language Changes for a ... enhancements, and removed or deprecated options for all JDK releases. Given an instance of a class, it is possible to use reflection to set the values of fields in that class....
🌐
LogicBig
logicbig.com › how-to › reflection › setting-field-value.html
Java - Different ways to Set Field Value by Reflection
April 3, 2020 - package com.logicbig.example; import org.springframework.beans.ConfigurablePropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; public class SpringPropertyAccessorExample { public static void main(String[] args) { Person p = new Person();//must have getters and setters System.out.println("before: " + p); ConfigurablePropertyAccessor propertyAccessor = PropertyAccessorFactory.forBeanPropertyAccess(p); propertyAccessor.setPropertyValue("name", "Tina"); System.out.println("after: " + p); } } before: Person{name='null'} after: Person{name='Tina'} Dependencies and Technologies Used: commons-beanutils 1.9.4: Apache Commons BeanUtils provides an easy-to-use but flexible wrapper around reflection and introspection. spring-beans 5.2.5.RELEASE: Spring Beans. JDK 8 · Maven 3.5.4 · java-reflection-setting-field-value ·
🌐
Baeldung
baeldung.com › home › java › set field value with reflection
Set Field Value With Reflection | Baeldung
January 8, 2024 - In this quick tutorial, we’ll discuss how can we set the values of fields from a different class in Java by using the Reflection API.
🌐
Coderanch
coderanch.com › t › 451509 › java › Setting-bean-throught-reflection
Setting value of a bean throught reflection (Java in General forum at Coderanch)
June 26, 2009 - For example if the propertyName ...ertyValue) Reflection allow you to access the methods too -- so you can convert the property name to its setter, by upcasing the first character, and prepending "set"....
Top answer
1 of 2
2

If your classes respect the JavaBeans convention (standard getters and setters encapsulate fields), you can use the Introspector, and several frameworks that rely on it.

My favorite example would be Spring's BeanWrapper technology, which allows you to write code like this:

BeanWrapper bw = new BeanWrapperImpl(street);
bw.setPropertyValue("buildings[0].appartments[1].owner", "luke");
2 of 2
1

I have just do a simply solution based on your Structure. This have a lot to be add (NullPointerException, OutOfBounds, ...) but for correct input, you have a correct answer.

Then you just need to methods, one to set a value, one to get a instance from a list. Both need to use reflection.

public Object getListItem(Object o, String name, int index) throws Exception{
    return ((List)o.getClass().getDeclaredField(name).get(o)).get(index);
}

public void setValue(Object o, String name, Object value) throws Exception{
    o.getClass().getDeclaredField(name).set(o, value);
}

Like a said, no checks are made, I did simple since I do that from scratch.

Then, just need to parse the String (again, no check) based on / to find each [variable/value] blocs. And find what type this is :

  • if it contains #, this is an attribution
  • if it contains ., this is a getter in a list

So this should looks like this.

public void init(Object o, String pattern) throws Exception{
    String[] array = pattern.split("/");
    for(String s : array){
        if(s.contains("#")){
            String[] param = s.split("\\#");
            setValue(o, param[0], param[1]);
        } else {
            String[] list = s.split("\\.");
            o = getListItem(o, list[0], Integer.parseInt(list[1]));
        }
    }
}

Following is the output from the example you can find on ideone here

That will output

[Street] Foo [
        [Building] 1 1[[Apartment] null, [Apartment] null], 
        [Building] 2 2[[Apartment] null, [Apartment] null, [Apartment] null, [Apartment] null], 
        [Building] 3 1[[Apartment] null, [Apartment] null]]
[Street] Foo [
        [Building] 1 1[[Apartment] null, [Apartment] null], 
        [Building] 2 3[[Apartment] null, [Apartment] null, [Apartment] null, [Apartment] null], 
        [Building] 3 1[[Apartment] null, [Apartment] null]]
[Street] Foo [
        [Building] 1 1[[Apartment] null, [Apartment] null], 
        [Building] 2 3[[Apartment] null, [Apartment] null, [Apartment] null, [Apartment] null], 
        [Building] 3 1[[Apartment] null, [Apartment] John]]
🌐
Avajava
avajava.com › tutorials › lessons › how-do-i-get-and-set-a-field-using-reflection.html
How do I get and set a field using reflection?
This is our free web tutorial index that features a variety of topics related to Java web application development.
Top answer
1 of 5
62

Hopefully this is what you are trying to do:

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Test {
    
    private Map ttp = new HashMap(); 
    
    public  void test() {
        Field declaredField =  null;
        try {
            
            declaredField = Test.class.getDeclaredField("ttp");
            boolean accessible = declaredField.isAccessible();

            declaredField.setAccessible(true);
            
            ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
            concHashMap.put("key1", "value1");
            declaredField.set(this, concHashMap);
            Object value = ttp.get("key1");

            System.out.println(value);

            declaredField.setAccessible(accessible);
            
        } catch (NoSuchFieldException 
                | SecurityException
                | IllegalArgumentException 
                | IllegalAccessException e) {
            e.printStackTrace();
        }
        
    }

    public static void main(String... args) {
        Test test = new Test();
        test.test(); 
    }
}

It prints :

value1
2 of 5
26

It's worth reading Oracle Java Tutorial - Getting and Setting Field Values

Field#set(Object object, Object value) sets the field represented by this Field object on the specified object argument to the specified new value.

It should be like this

f.set(objectOfTheClass, new ConcurrentHashMap<>());

You can't set any value in null Object If tried then it will result in NullPointerException


Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.

Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-reflection-example-tutorial
Java Reflection Example Tutorial | DigitalOcean
August 3, 2022 - If the field is final, the set() methods throw java.lang.IllegalAccessException. We know that private fields and methods can’t be accessible outside of the class but using reflection we can get/set the private field value by turning off the java access check for field modifiers.
🌐
GeeksforGeeks
geeksforgeeks.org › java › field-set-method-in-java-with-examples
Field set() method in Java with Examples - GeeksforGeeks
January 10, 2023 - The set() method of java.lang.reflect.Field is used to set the value of the field represented by this Field object on the specified object argument to the specified new value passed as parameter.
🌐
Apache NetBeans
bits.netbeans.org › dev › javadoc › org-openide-nodes › org › openide › nodes › PropertySupport.Reflection.html
PropertySupport.Reflection (Nodes API)
The getter and setter methods are constructed by capitalizing the first letter in the name of propety and prefixing it with get and set, respectively. ... Test whether the property is readable. ... public T getValue() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException ... Get the value. ... Test whether the property is writable. ... Set the value. ... Get a property editor for this property. The default implementation uses standard Java PropertyEditorManager.
🌐
Medium
medium.com › @himani.prasad016 › java-reflection-inspecting-and-modifying-java-objects-at-runtime-512a5927a220
Java Reflection: Inspecting and Modifying Java Objects at Runtime | by Himani Prasad | Medium
March 23, 2023 - Reflection is the ability of a program to examine and modify its own structure and behavior at runtime. In Java, this is achieved through the use of special classes and methods in the java.lang.reflect package. In Java, everything is an object, and every object has a Class object that describes its properties and behavior.
🌐
Intertech
intertech.com › home › using spring’s reflectionutils to access private fields
Using Spring's ReflectionUtils to Access Private Fields - Intertech
February 13, 2024 - This step uses the Spring ReflectionUtils.setField method to set the value on the object. This method takes three arguments, the Field reference, the object to set the value on, and the value to set.
🌐
Java2Blog
java2blog.com › home › core java › reflection › get and set fields using reflection in java
Get and set Fields using reflection in java - Java2Blog
January 11, 2021 - java.lang.reflect.Field can be used to get/set fields(member variables) at runtime using reflection.
🌐
Stack Overflow
stackoverflow.com › questions › 72331203 › setting-object-properties-using-reflection-and-annotation-in-java
Setting Object Properties using Reflection and Annotation in Java - Stack Overflow
May 21, 2022 - public class Component { private String name; private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } ... @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Properties { String compName(); }
🌐
Codemia
codemia.io › knowledge-hub › path › set_object_property_using_reflection
Set object property using reflection
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
Top answer
1 of 2
2

Reflection seems a very fragile and non-intuitive way to implement this. Instead I think you should be telling the objects what to do, and they will collaborate between themselves to determine this. e.g.

restaurant.switchToSpringMenu();

and the Restaurant object could swap between menu instances that it has.

Exact requirement is that I will be getting some task to be done and corresponding value.. Now every task can be at different level in the hierarchy of the class... So I am not how else should I implement this

Perhaps this could be achieved via a visitor pattern. e.g. you do something like:

restaurant.reorganise(forSummer);

where forSummer is some implementation of a task. The Restaurant object collaborates with this task object, then calls on the underlying Employee/Menu classes, which will do the same.

If you really want a more generic means of navigating these hierarchies, you could look at JXPath, which allows you to use XPath-like expressions to find objects e.g.

 (Ingredient)JXPathContext.newContext(restaurants).
         getValue("restaurant[address/zipCode='90210']/menu/ingredients[1]");
2 of 2
1

This is a very bad idea. You shouldn't be doing this. If you really want to do this, stop using java -- it's totally inappropriate for the task at hand. You seem to not understand OO -- if you did you wouldn't be asking this question. Java, despite its common misuses, is an OO language and should be treated as such.

The first thing you should try is polymorphism. Have all the classes implement a basic tree/graph interface and a setValue() method that sets the value on the given object and walks the graph to each related object also calling setValue().

The next thing you should try is an event driven approach. Have objects register as event handlers, then raise an event containing the value to be set. Have the handlers set the appropriate values in the appropriate way.

If you use reflection you'll end up with unreadable/unmaintainable code that is very error prone and which will probably stop working as soon as you upgrade java or change a class. It will have a very short shelf-life.