Iterating field object in java
In Java, to iterating over the fields (variables) of a class, reflection can be used. Reflection allows you to inspect classes, interfaces, fields, and methods at runtime.
Example we have have Book.java entity which has various fields such as id, name, code, description.
package com.techbug.techbug.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; @Table(name="book") @Entity public class Book{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "name", nullable = false) private String name; @Column(name = "code", nullable = false) private String code; @Column(name = "description", nullable = false) private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Book(long id, String code, String name, String description) { this.id =id; this.code =code; this.name = name; this.description= description; } public Book() {} }
BookService.java
public void readBookById(Long Id) throws IllegalArgumentException, IllegalAccessException { log.debug("Method called to readBookById",Id); Optional<Book> book = bookRepository.findById(Id); Class<?> clazz = Book.class; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object value = field.get(book.get()); System.out.println("Field name: " + field.getName()); System.out.println("Field type: " + field.getType()); System.out.println("Field value: " + value); System.out.println("-----------------------------------"); } }
Field
class from the java.lang.reflect
package. This package contains classes and interfaces that provide access to the reflection functionality in Java. Here getDeclaredFields() retrieve all fields of Book class. Now upon Iterating field object we will be seeing all available fields along with data type and name.
Output of Above code:
A Step-by-Step Tutorial For Creating Spring Boot Application
Building Spring Boot Rest Api in Java
Java Hibernate Magic: Create MySQL Tables with Ease and Efficiency