Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to set an object property

I getting class by name and i need to update them with respective data and my question is how to do it with java I want to add the method some dummy data . I don't know the class type I just getting the class name and use reflection to get his data

I use this code to get the class instance and

Class<?> classHandle = Class.forName(className);  Object myObject = classHandle.newInstance();  // iterate through all the methods declared by the class for (Method method : classHandle.getMethods()) {     // find all the set methods     if (method.getName().matches("set[A-Z].*") 

And know that I find the list of the set method I want to update it with data how can I do that .

assume that In class name I got person and the class have setSalary and setFirstName etc how can I set them with reflection ?

public class Person {      public void setSalery(double salery) {         this.salery = salery;     }      public void setFirstName(String FirstName) {         this.FirstName = FirstName;     }    } 
like image 825
Stefan Strooves Avatar asked Jan 17 '13 08:01

Stefan Strooves


People also ask

How do I set the properties of an object in Java?

You can set properties at object initialization by providing property-value pairs in a call to the object's Init method: Obj = OBJ_NEW('ObjectClass', PROPERTY = value, ... )

What is C# reflection?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

How do I copy values from one object to another in C#?

In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.


2 Answers

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"); 
like image 144
sp00m Avatar answered Oct 08 '22 08:10

sp00m


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"); 
like image 45
paralaks Avatar answered Oct 08 '22 08:10

paralaks