Free Data Structures and Algorithms Course









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










OR



Subscribe to all free courses

How to determine fields in a class using Java Reflection API ?.

Program to demonstrate how to determine fields in a class using Java Reflection API

package com.hubberspot.reflection;

import java.lang.reflect.Field;

// Creating two simple Java classes such as
// Car and Ferrari. Giving it a parent and child 
// relationship. As Ferrari is a Car
class Car 
{
 // Creating two public fields in Car
 public int tyres;
 public int doors;
}

class Ferrari extends Car 
{
 // Creating two fields in Ferrari which are 
 // protected and private
 protected String engine;
 private int windows;
}


public class ClassFieldsFinding {

 public static void main(String[] args) {

  // Creating a instance of class Class of type Ferrari
  Class ferrariClass = Ferrari.class;

  // In order to get public fields name and type at 
  // runtime we 
  Field [] ferrariFields = ferrariClass.getFields();

  System.out.println("Ferrari has following fields : ");

  for(int i = 0; i < ferrariFields.length; i++) {

   // Field class has a method by name getName()
   // which returns back the name of the field
   String fieldName = ferrariFields[i].getName();

   // Field class has a method by name getType()
   // which returns instance of Class of the type
   Class fieldType = ferrariFields[i].getType();

   // Calling the getName() returns us back the 
   // name of the type
   String fieldTypeName = fieldType.getName();

   System.out.println(i+1 + ". Field Name : " + fieldName + 
     " Field Type : " +fieldTypeName);

  }

  // getFields method returns us the public fields of the 
  // class. In order to get the name of private and protected
  // fields of the class and its superclass we usually
  // call getDeclaredFields() method on the Class instance 
  ferrariFields =  ferrariClass.getDeclaredFields();

  for(int i = 0; i < ferrariFields.length; i++) {

   String fieldName = ferrariFields[i].getName();

   // It returns back the name of fields 
   // which are private and protected 
   Class fieldType = ferrariFields[i].getType();

   String fieldTypeName = fieldType.getName();

   System.out.println(i+3 + ". Field Name : " + fieldName + 
     " Field Type : " +fieldTypeName);

  }
 }
}


Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot