Set field value with reflection

java reflection set private field value
java reflection set field value by name
reflection change value of field
how to set values to object in java
java reflection get field value from object
how to set value in annotated field in java
java annotation set field value
java reflection get all fields

I'm working with one project which is not opensource and I need to modify one or more its classes.

In one class is following collection:

private Map<Integer, TTP> ttp = new HashMap<>(); 

All what I need to do is use reflection and use concurrenthashmap here. I've tried following code but it doesnt work.

Field f = ..getClass().getDeclaredField("ttp");
f.setAccessible(true);
f.set(null, new ConcurrentHashMap<>());

Hope this is something 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

Set field value with reflection, Hope this is something what you are trying to do : import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import  Examples. The following example sets the value of a field, gets and displays the value, modifies the field, and displays the result. using namespace System; using namespace System::Reflection; using namespace System::Globalization; public ref class Example { private: String^ myString; public: Example() { myString = "Old value"; } property String^ StringProperty { String^ get() { return

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.

How to set field values using Java reflection, In addition, via the Field class we can get and set the value of a field in a given object. The most generic method to set a field value is set(Object obj, Object value):  Set private field value with reflection. Ask Question Asked 4 years, 8 months ago. Active 6 months ago. Viewed 78k times 64. 15. I have 2

The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}

Field set() method in Java with Examples, 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. I'd like to set a property of an object through Reflection, with a value of type string. So, for instance, suppose I have a Ship class, with a property of Latitude, which is a double. Here's what I'd like to do:

You can try this:

//Your class instance
Publication publication = new Publication();

//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");

//Get method
Method  method = c.getDeclaredMethod ("setTitle", String.class);

//set value
method.invoke (publication,  "Value to want to set here...");

How do I get and set a field using reflection?, You can set the value of the field by calling the set() method on the Field object, where the first parameter is the object that has the field value that you'd like to set,​  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.

You can try this:

static class Student {
    private int age;
    private int number;

    public Student(int age, int number) {
        this.age = age;
        this.number = number;
    }

    public Student() {
    }
}
public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
    Student student1=new Student();
   // Class g=student1.getClass();
    Field[]fields=student1.getClass().getDeclaredFields();
    Field age=student1.getClass().getDeclaredField("age");
    age.setAccessible(true);
    age.setInt(student1,13);
    Field number=student1.getClass().getDeclaredField("number");
    number.setAccessible(true);
    number.setInt(student1,936);

    for (Field f:fields
         ) {
        f.setAccessible(true);

        System.out.println(f.getName()+" "+f.getInt(student1));

    }
}

}

Java Reflection - Fields, Java Reflection - Fields. Obtaining Field Objects; Field Name; Field Type; Getting and Setting Field Values  Java Reflection provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.

FieldInfo.SetValue Method (System.Reflection), Sets the value of the field for the given object to the given value. 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. The new value is automatically unwrapped if the underlying field has a primitive type.

Java Reflection - Field.set() Examples, Method: public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException. Sets this field value for the provided object. If the resulting array has 0 (zero) elements, the property is not indexed. To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null, the property will be set to the default value for that type.

Java - Different ways to Set Field Value by Reflection, This tutorial shows different ways to set field values by using Java Reflection. Examples. Example POJO. public class Person { private  Examples. The following example uses the GetValue method to retrieve the value of a static field. Note that the value of the obj argument is null.. using namespace System; using namespace System::Reflection; ref class Example { public: static String^ val = "test"; }; int main() { FieldInfo^ fld = Example::typeid->GetField( "val" ); Console::WriteLine(fld->GetValue(nullptr) ); Example::val

Comments
  • What does it mean: but it doesnt work? On which object do you call .getClass().getDeclaredField("ttp")
  • I looking for some code for copy all field values from a class to another. But the fields are not just native types. It's possible?
  • @Krismorte "fields are not just native types" means? for instance?
  • @Krismorte Late as @#$%, but possible - yes. Sounds like you're looking for a "bean to bean mapper" one example you may be interested in is github.com/DozerMapper/dozer
  • @Visruth Means fields like "HisOwnClass" rather than "int" or "Integer" etc.