Java reflection change field value

Get/Set field value

We can get field value with reflection methods and they returns primitive types. The following lists have all methods we need to know.

  • Object get(Object obj) Returns field value
  • boolean getBoolean(Object obj) Gets field value as boolean.
  • byte getByte(Object obj) Gets field value as byte.
  • char getChar(Object obj) Gets field value as char.
  • double getDouble(Object obj) Gets field value as double.
  • float getFloat(Object obj) Gets field value as float.
  • Type getGenericType() Returns a Type object that represents the declared type for the field represented by this Field object.
  • int getInt(Object obj) Gets field value as int.
  • long getLong(Object obj) Gets field value as long.
  • short getShort(Object obj) Gets field value as short.

import java.awt.Rectangle; import java.lang.reflect.Field; /*java 2 s .co m*/ public class Main < public static void main(String[] args) < Rectangle r = new Rectangle(100, 325); Class c = r.getClass(); try < Field heightField = c.getField("height"); Integer heightValue = (Integer) heightField.get(r); System.out.println("Height: " + heightValue.toString()); > catch (NoSuchFieldException e) < System.out.println(e); >catch (SecurityException e) < System.out.println(e); >catch (IllegalAccessException e) < System.out.println(e); >> > 

Set field value with Reflection

We can also set the value back to a field with reflection.

  • void set(Object obj, Object value) Sets the field value.
  • void setBoolean(Object obj, boolean z) Sets boolean field value.
  • void setByte(Object obj, byte b) Sets byte field value.
  • void setChar(Object obj, char c) Sets char field value.
  • void setDouble(Object obj, double d) Sets double field value.
  • void setFloat(Object obj, float f) Sets float field value.
  • void setInt(Object obj, int i) Sets int field value.
  • void setLong(Object obj, long l) Sets long field value.
  • void setShort(Object obj, short s) Sets short field value.

import java.awt.Rectangle; import java.lang.reflect.Field; /* ja v a 2s. c o m*/ public class Main < public static void main(String[] args) < Rectangle r = new Rectangle(100, 325); Class c = r.getClass(); try < Field heightField = c.getField("height"); heightField.setInt(r, 1000); Integer heightValue = (Integer) heightField.get(r); System.out.println("Height: " + heightValue.toString()); > catch (NoSuchFieldException e) < System.out.println(e); >catch (SecurityException e) < System.out.println(e); >catch (IllegalAccessException e) < System.out.println(e); >> > 

Get/set field value and possible exceptions

The following code gets and sets the values of instance and class fields

import java.lang.reflect.Field; /*from ja v a 2 s. c om*/ class X < public int i = 10; public static final double PI = 3.14; > public class Main < public static void main(String[] args) throws Exception < Classclazz = Class.forName("X"); X x = (X) clazz.newInstance(); Field f = clazz.getField("i"); System.out.println(f.getInt(x)); // Output: 10 f.setInt(x, 20); System.out.println(f.getInt(x)); // Output: 20 f = clazz.getField("PI"); System.out.println(f.getDouble(null)); // Output: 3.14 f.setDouble(x, 20); > > 

Here is the output from the code above. The exception is for the final static field PI . public final static field defines a constant in Java and we cannot reset a value for a constant through reflection.

Next chapter.

What you will learn in the next chapter:

Источник

Getting and Setting Field Values

Given an instance of a class, it is possible to use reflection to set the values of fields in that class. This is typically done only in special circumstances when setting the values in the usual way is not possible. Because such access usually violates the design intentions of the class, it should be used with the utmost discretion.

The Book class illustrates how to set the values for long, array, and enum field types. Methods for getting and setting other primitive types are described in Field .

import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out; enum Tweedle < DEE, DUM >public class Book < public long chapters = 0; public String[] characters = < "Alice", "White Rabbit" >; public Tweedle twin = Tweedle.DEE; public static void main(String. args) < Book book = new Book(); String fmt = "%6S: %-12s = %s%n"; try < Classc = book.getClass(); Field chap = c.getDeclaredField("chapters"); out.format(fmt, "before", "chapters", book.chapters); chap.setLong(book, 12); out.format(fmt, "after", "chapters", chap.getLong(book)); Field chars = c.getDeclaredField("characters"); out.format(fmt, "before", "characters", Arrays.asList(book.characters)); String[] newChars = < "Queen", "King" >; chars.set(book, newChars); out.format(fmt, "after", "characters", Arrays.asList(book.characters)); Field t = c.getDeclaredField("twin"); out.format(fmt, "before", "twin", book.twin); t.set(book, Tweedle.DUM); out.format(fmt, "after", "twin", t.get(book)); // production code should handle these exceptions more gracefully > catch (NoSuchFieldException x) < x.printStackTrace(); >catch (IllegalAccessException x) < x.printStackTrace(); >> >

This is the corresponding output:

$ java Book BEFORE: chapters = 0 AFTER: chapters = 12 BEFORE: characters = [Alice, White Rabbit] AFTER: characters = [Queen, King] BEFORE: twin = DEE AFTER: twin = DUM

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.

Use of reflection can cause some runtime optimizations to be lost. For example, the following code is highly likely be optimized by a Java virtual machine:

Equivalent code using Field.set*() may not.

Источник

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 String name; public String getName() < return name; >public void setName(String name) < this.name = name; >@Override public String toString() < return "Person'; > >

Using java.lang.reflect.Field

package com.logicbig.example; import java.lang.reflect.Field; public class JavaFieldExample < public static void main(String[] args) throws Exception < Person p = new Person(); System.out.println("before: "+p); Field field = Person.class.getDeclaredField("name"); field.setAccessible(true); field.set(p, "Tina"); field.setAccessible(false); System.out.println("after: "+p); >>
before: Person
after: Person

Invoking setter via java.lang.reflect.Method

package com.logicbig.example; import java.lang.reflect.Method; public class JavaSetterMethodExample < public static void main(String[] args) throws Exception < Person p = new Person();//must have setter System.out.println("before: "+p); Method setter = Person.class.getDeclaredMethod("setName", String.class); setter.invoke(p, "Tina"); System.out.println("after: "+p); >>
before: Person
after: Person

Using BeanInfo

package com.logicbig.example; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.Arrays; import java.util.Optional; public class JavaBeanInfoExample < public static void main(String[] args) throws Exception < Person p = new Person();//must have getters and setters System.out.println("before: " + p); BeanInfo beanInfo = Introspector.getBeanInfo(Person.class); OptionalpropertyDescriptor = Arrays.stream(beanInfo.getPropertyDescriptors()) .filter(pd -> pd.getName().equals("name")) .findAny(); if (propertyDescriptor.isPresent()) < propertyDescriptor.get().getWriteMethod().invoke(p, "Tina"); System.out.println("after: " + p); >> >
before: Person
after: Person

Using Commons BeanUtils

pom.xml

 commons-beanutils commons-beanutils 1.9.4 
package com.logicbig.example; import org.apache.commons.beanutils.BeanUtils; public class ApacheCommonBeanUtilsExample < public static void main(String[] args) throws Exception < Person p = new Person();//must have getters and setters System.out.println("before: " + p); BeanUtils.setProperty(p, "name", "Tina"); System.out.println("after: " + p); >>
before: Person
after: Person

Using Spring beans

pom.xml

 org.springframework spring-beans 5.2.5.RELEASE 

Direct field Access

package com.logicbig.example; import org.springframework.beans.ConfigurablePropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; public class SpringFieldAccessorExample < public static void main(String[] args) < Person p = new Person(); System.out.println("before: "+p); ConfigurablePropertyAccessor propertyAccessor = PropertyAccessorFactory.forDirectFieldAccess(p); propertyAccessor.setPropertyValue("name", "Tina"); System.out.println("after: "+p); >>
before: Person
after: Person

Setter access

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
after: Person

Example Project

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

Источник

Get and Set Field Value using Reflection in Java

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. Also provides the possibility to instantiate new objects, invoke methods and get/set field values.

Here is an example how to get and set field values.

Example

For testing will create a simple class with 3 fields: first public, second private and third protected.

package com.admfactory.reflect; public class Username < public int id; private String name; protected String email; public Username() < >public int getId() < return id; >public void setId(int id) < this.id = id; >public String getName() < return name; >public void setName(String name) < this.name = name; >public String getEmail() < return email; >public void setEmail(String email) < this.email = email; >public void display() < System.out.println(String.format("Username: [id:%d, name:%s, email:%s]", id, name, email)); >> 

Here is an example how to set and get the fields using reflection.

package com.admfactory.reflect; import java.lang.reflect.Field; public class FieldTest < public static void main(String[] args) throws Exception < System.out.println("get and set fild values using reflection example"); Username user = new Username(); System.out.println(); Classclazz = Username.class; Field fieldID = clazz.getField("id"); fieldID.set(user, 100); System.out.println("Id value set using reflection: " + user.id); int value get using reflection: " + id); System.out.println(); Field fieldNAME = clazz.getDeclaredField("name"); fieldNAME.setAccessible(true); fieldNAME.set(user, "Admin"); System.out.println("Name value set using reflection: " + user.getName()); String name = (String) fieldNAME.get(user); System.out.println("Name value get using reflection: " + name); Field fieldEMAIL = clazz.getDeclaredField("email"); fieldEMAIL.setAccessible(true); fieldEMAIL.set(user, "admin@example.com"); System.out.println("Email value set using reflection: " + user.getEmail()); String email = (String) fieldEMAIL.get(user); System.out.println("Email value get using reflection: " + email); System.out.println(); user.display(); > > 

If you want to get the public field you can use getField method, for private or protected fields you need to use getDeclaredField method. As a best practice you can always use getDeclaredField method. Also for private and protected fields you need to set the field as accessible, otherwise an java.lang.IllegalAccessException exception will be thrown.

Output

get and set fild values using reflection example Id value set using reflection: 100 Id value get using reflection: 100 Name value set using reflection: Admin Name value get using reflection: Admin Email value set using reflection: admin@example.com Email value get using reflection: admin@example.com Username: [id:100, name:Admin, email:admin@example.com]

References

Источник

Читайте также:  Php url links net
Оцените статью