Create Entity Class
Create entities package and create new class named Student as below:
package entities;
public class Student {
private String id;
private String name;
private int age;
public String address;
public String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
}
public Student(String id) {
this.id = id;
}
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
Run Application
package reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import entities.Student;
public class Main {
private static void displayAllFields(Student student) {
Class studentClass = student.getClass();
Field[] fields = studentClass.getFields();
System.out.println("Count 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("============================");
}
}
public static void main(String[] args) {
Student student = new Student();
displayAllFields(student);
}
}
Output
Count Fields: 2
Field Name: address
Field Type: java.lang.String
============================
Field Name: email
Field Type: java.lang.String
============================