Java reflection set all fields

Java Reflection — Fields

Using Java Reflection you can inspect the fields (member variables) of classes and get / set them at runtime. This is done via the Java class java.lang.reflect.Field . This text will get into more detail about the Java Field object. Remember to check the JavaDoc from Sun out too.

Obtaining Field Objects

The Field class is obtained from the Class object. Here is an example:

Class aClass = . //obtain class object Field[] fields = aClass.getFields();

The Field[] array will have one Field instance for each public field declared in the class.

If you know the name of the field you want to access, you can access it like this:

Class aClass = MyObject.class Field field = aClass.getField("someField");

The example above will return the Field instance corresponding to the field someField as declared in the MyObject below:

Читайте также:  Php передача файла клиенту

If no field exists with the name given as parameter to the getField() method, a NoSuchFieldException is thrown.

Field Name

Once you have obtained a Field instance, you can get its field name using the Field.getName() method, like this:

Field field = . //obtain field object String fieldName = field.getName();

Field Type

You can determine the field type (String, int etc.) of a field using the Field.getType() method:

Field field = aClass.getField("someField"); Object fieldType = field.getType();

Getting and Setting Field Values

Once you have obtained a Field reference you can get and set its values using the Field.get() and Field.set() methods, like this:

Class aClass = MyObject.class Field field = aClass.getField("someField"); MyObject objectInstance = new MyObject(); Object value = field.get(objectInstance); field.set(objetInstance, value);

The objectInstance parameter passed to the get and set method should be an instance of the class that owns the field. In the above example an instance of MyObject is used, because the someField is an instance member of the MyObject class.

It the field is a static field (public static . ) pass null as parameter to the get and set methods, instead of the objectInstance parameter passed above.

Источник

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.

Источник

Get and set Fields using reflection in java

In this post, we will see how to get and set fields using reflection in java.

java.lang.reflect.Field can be used to get/set fields(member variables) at runtime using reflection.

Get all fields of the class

All fields of the class can be obtained from the Class object. Here is an example.

Field[] will have all the public fields of the class.

Get particular field of the class

If you already know name of the fields you want to access, you can use cl.getField(String fieldName) to get Field object.

Getting and setting Field value

Field.get() and Field.set() methods can be used get and set value of field respectively.
Let’s understand with the help of example.
Consider a class named Employee which consists of two private fields name and age .

Create main class named PrivateFieldReflectionMain

> catch ( SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e )

When you run above class, you will get below output:
Output:

Please note that Here parameter to get() and set() should be object of the class to which field belongs.
For example:
In this case, name field belongs to Employee class, we have passed e to get() and set() method of field object.

Getting and setting static Field value

In case, you want to get and set static field, then you need to pass null while using get() and set() method of Field.
For example:

then you can get and set field as below:

That’s all about how to get and set Fields using reflection in java.

Was this post helpful?

Share this

Author

Access private fields and methods using reflection in java

Table of ContentsAccess private fieldAccess private method In this post, we will see how to access private fields and methods using reflection in java. Can you access private fields and methods using reflection? Yes, you can. It is very easy as well. You just need to call .setAccessible(true) on field or method object which you […]

Invoke constructor using Reflection in java

Table of ContentsInstantiate Constructor with no parametersInstantiate Constructor with parametersConstructor parameters for primitive typesConclusion In this post, we will see how to invoke constructor using reflection in java. You can retrieve the constructors of the classes and instantiate object at run time using reflection. java.lang.reflect.Constructor is used to instantiate the objects. Instantiate Constructor with no […]

Invoke Getters And Setters Using Reflection in java

Table of ContentsUsing PropertyDescriptorUsing Class’s getDeclaredMethods In this post, we will see how to call getters and setters using reflection in java. We have already seen how to invoke method using reflection in java. There are two ways to invoke getter and setter using reflection in java. Using PropertyDescriptor You can use PropertyDescriptor to call […]

How to invoke method using reflection in java

Table of ContentsInvoke method without parametersInvoke method with parametersInvoke static method using reflectionInvoke private method using reflection In this post, we will see how to invoke the method using reflection in java. Let’s understand this with the help of the example. Create a class named Employee.java. We will invoke this class’s method using reflection. [crayon-64bd2d89207e6501520756/] […]

Java Reflection tutorial

Table of ContentsIntroductionThe ‘reflect’ packageFieldModifierProxyMethodConstructorArrayUses of Reflection in JavaExtensibilityDeveloping IDEs and Class BrowsersDebugging and Testing toolsDisadvantages of ReflectionLow PerformaceSecurity RiskExposure of Internal Fields and AttributesJava.lang.Class – the gateway to ReflectionImportant Methods of java.lang.ClassforName() method:getConstructors() and getDeclaredConstructors() methods:getMethods() and getDeclaredMethods()getFields() and getDeclaredFields() methods:Conclusion Introduction Reflection, as we know from the common term, is an image of […]

Источник

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

Источник

Оцените статью