Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Using Reflection API for getting fields name and type of objects in Java

Program to demonstrate Usage of Reflection API for getting fields name and type in Java

package com.hubberspot.example;

import java.lang.reflect.Field;

class Employee {
 public String firstname;
 protected String lastname;
 private String email;
 static int counter;
}

public class EmployeeTest {

   public static void main(String[] args) {

 // Create a test object. We can create
 // and apply reflection on any class 
 // we want without knowing which fields
 // it has. We are taking Employee here. 
 Employee employee = new Employee();

 // Getting Class associated with Employee
 Class employeeClass = employee.getClass();  

 System.out.println("-----------------------------------");

 try {
 // Using Field class we can get field of any
 // class we want. Here we are getting field
 // firstname by calling getField method of the
 // Class associated with Employee with public specifier 
 Field singleField = employeeClass.getField("firstname");

 // getName returns the name of the field
 System.out.println("Field name = " + singleField.getName());

 // getType().getName() returns the type of the field
 System.out.println("Field type = " + singleField.getType().getName());

 System.out.println("-----------------------------------");

 // getDeclaredFields methods returns array of fields which
 // involve all fields irrespective of access specifier such as
 // public, private, protected and default
 Field[] declaredFields = employeeClass.getDeclaredFields();
 System.out.println("Number of fields = " + declaredFields.length);

 for (Field field : declaredFields) {
           System.out.println("Field name = " + field.getName());
    System.out.println("Field type = " + field.getType().getName());   
 }

 System.out.println("-----------------------------------");

 // getFields methods returns array of fields which
 // involve fields only with access specifier as public
 Field[] fields = employeeClass.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());
 }

    } catch (SecurityException e) {

  e.printStackTrace();
    } catch (NoSuchFieldException e) {

  e.printStackTrace();
    }

  }

}




Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot