Java object get field by name

Java.lang.Class.getField() Method

The java.lang.Class.getField() returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field.

Declaration

Following is the declaration for java.lang.Class.getField() method

public Field getField(String name) throws NoSuchFieldException, SecurityException

Parameters

name − This is the field name.

Return Value

This method returns the Field object of this class specified by name.

Exception

  • NoSuchFieldException − If a field with the specified name is not found.
  • NullPointerException − If name is null
  • SecurityException − If a security manager, s, is present.

Example

The following example shows the usage of java.lang.Class.getField() method.

package com.tutorialspoint; import java.lang.reflect.*; public class ClassDemo < public static void main(String[] args) < ClassDemo c = new ClassDemo(); Class cls = c.getClass(); System.out.println("Field ="); try < // string field Field sField = cls.getField("string1"); System.out.println("Public field found: " + sField.toString()); >catch(NoSuchFieldException e) < System.out.println(e.toString()); >> public ClassDemo() < // no argument constructor >public ClassDemo(String string1) < this.string1 = string1; >public String string1 = "tutorialspoint"; >

Let us compile and run the above program, this will produce the following result −

Field = Public field found: public java.lang.String ClassDemo.string1

Источник

How do I get fields of a class object?

The example below using reflection to obtain the fields of a class object. We’ll get the field names and their corresponding type. There are three ways shown below which can be used to get an object fields:

package org.kodejava.lang.reflect; import java.util.Date; import java.lang.reflect.Field; public class GetFields < public Long id; protected String name; private Date birthDate; Double weight; public static void main(String[] args) < GetFields object = new GetFields(); Classclazz = object.getClass(); // Get all object fields including public, protected, package and private // access fields. Field[] fields = clazz.getDeclaredFields(); System.out.println("Number of fields = " + fields.length); for (Field field : fields) < System.out.println("Field name = " + field.getName()); System.out.println("Field type = " + field.getType().getName()); >System.out.println("\n----------------------------------------\n"); // Get all object accessible public fields. fields = clazz.getFields(); System.out.println("Number of fields = " + fields.length); for (Field field : fields) < System.out.println("Field name = " + field.getName()); System.out.println("Field type = " + field.getType().getName()); >System.out.println("\n----------------------------------------\n"); try < // Get field name id with public access modifier Field field = clazz.getField("id"); System.out.println("Field name = " + field.getName()); System.out.println("Field type language-text">Number of fields = 4 Field name = id Field type = java.lang.Long Field name = name Field type = java.lang.String Field name = birthDate Field type = java.util.Date Field name = weight Field type = java.lang.Double ---------------------------------------- Number of fields = 1 Field name = id Field type = java.lang.Long ---------------------------------------- Field name = id Field type = java.lang.Long 

A programmer, recreational runner and diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

Источник

Читайте также:  Java iterator foreachremaining example

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:

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.

Читайте также:  Add spaces with html

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.

Источник

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:

Читайте также:  Проверить делится ли число нацело python

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-64b7d2e94ed6f062414517/] […]

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 […]

Источник

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