Free Data Structures and Algorithms Course









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










OR



Subscribe to all free courses
Showing posts with label Reflection in Java. Show all posts
Showing posts with label Reflection in Java. Show all posts

How to load and instantiate Java class dynamically using Java Reflection API ? (Video Tutorial)



Video tutorial to demonstrate how to load and instantiate Java class dynamically using Java Reflection API.






How to determine class modifiers dynamically using Java Reflection API ? (Video Tutorial)



Video tutorial to demonstrate how to determine class modifiers dynamically using Java Reflection API.






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 : 


 

How to determine information about class methods at runtime using Java Reflection API ?.

Program to demonstrate how to determine information about class methods at runtime using Java Reflection API.

package com.hubberspot.reflection;

import java.lang.reflect.Method;

// Create a dummy class having methods which are 
// private, protected and public. It should have
// a return type and few parameters.

class Cricket {

 private int runs;
 private String playerName;


 public void setRun(int runs) {

 }

 protected int getRun(int rate) {
  return rate*runs;
 }

 private void playerName( String name ) {
  playerName = name;
 }

 public void playerRuns(int rate , int runs , String playerName) {

 }

}

public class MethodFindings {

 public static void main(String[] args) {

  // Creating a instance of class Class of type Cricket
  Class cricketClass = Cricket.class;

  // object of class Instance has a method by name 
  // getMethods() which returns back a list of
  // public methods in the form of array
  // The array type is of Method class
  Method[] methodsArr = cricketClass.getMethods();

  for (int j = 0; j < methodsArr.length; j++) {

   // Method class has method by name getName()
   // which returns back the name of the method
   String methodName = methodsArr[j].getName();

   System.out.println("Name of the method : " + methodName);

   // Method class also has a method by name getReturnTypes()
   // which returns a Class object that represents the formal 
   // return type of the method represented by Method object. 
   String returnType =
     methodsArr[j].getReturnType().getName();

   System.out.println("Return Type of the method : " + returnType);

   // Method class also has a method called as getParameterTypes(). 
   // Returns an array of Class objects of parameter types, 
   // in declaration order. Returns an array of length 0 if 
   // the underlying method takes no parameters.

   Class[] parameterTypes =
     methodsArr[j].getParameterTypes();

   System.out.print("Parameter Types in the method :");

   for (int k = 0; k < parameterTypes.length; k ++) {

    String paramTypeName = parameterTypes[k].getName();

    System.out.print(" " + paramTypeName);
   }
   System.out.println();
  }

  System.out.println("-------------------------------------------");
  System.out.println("For methods that are declared private and protected etc... ");

  // Class object also has a method by name getDeclaredMethods().
  // Returns an array of Method objects reflecting all the methods 
  // declared by the class. This includes public, protected, 
  // default access and private methods, but excludes inherited methods. 

  // Rest of the code is same as above ..... 

  methodsArr = cricketClass.getDeclaredMethods();

  for (int j = 0; j < methodsArr.length; j++) {

   String methodName = methodsArr[j].getName();

   System.out.println("Name of the method : " + methodName);

   String returnType =
     methodsArr[j].getReturnType().getName();

   System.out.println("Return Type of the method : " + returnType);

   Class[] parameterTypes =
     methodsArr[j].getParameterTypes();

   System.out.print("Parameter Types in the method :");

   for (int k = 0; k < parameterTypes.length; k ++) {

    String paramTypeName = parameterTypes[k].getName();

    System.out.print(" " + paramTypeName);
   }
   System.out.println();
  }

 }

}


Output of the program : 



 

How to determine information about class constructor at runtime using Java Reflection API ?.

Program to demonstrate how to determine information about class constructor at runtime using Java Reflection API.

package com.hubberspot.reflection;

import java.lang.reflect.Constructor;

// Create a class Employee with few constructor
// having access modifiers as : public , private
// default and protected

class Employee {

 public Employee(int salary, String name) {

 } 

 private Employee(String name, int salary) {

 }

 Employee(String name) {

 }

 protected Employee(int salary) {

 }
}

public class ConstructorFindings {

 public static void main(String[] args) {

  // Creating a instance of class Class of type Employee
  Class employeeClass = Employee.class;

  // object of class Instance has a method by name 
  // getConstructors() which returns back a list of
  // public constructors in the form of array
  // The array type is of Constructor class
  Constructor[] constructors = employeeClass.getConstructors();

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

   // Constructor class defines a method called as getParameterTypes()
   // which returns back an array of Class objects having metadata
   // for types of arguments used in the constructor

   Class[] parametersArr = constructors[i].getParameterTypes();

   System.out.print("Constructor is : public having arguments as : ");

   for(int j = 0; j < parametersArr.length; j++) {

    String parameterType ="";

    // printing the type of argument passed to the constructor 
    parameterType = parametersArr[j].getName();

    System.out.print(parameterType+" ");

   }
  }

  // In order to get information of constructors other than public 
  // we use getDeclaredConstructors() method on the instance of the 
  // Class (Employee). It returns back array of constructors having
  // access modifiers including public.

  constructors = employeeClass.getDeclaredConstructors();

  System.out.println("\n\nEmployee has other constructor with type as : ");

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

   Class[] parametersArr = constructors[i].getParameterTypes();

   for(int j = 0; j < parametersArr.length; j++) {

    String parameterType ="";

    parameterType = parametersArr[j].getName();

    System.out.print(parameterType+" ");

   }
  }
 }
}


Output of the program : 


 

How to determine Interfaces implemented by a class dynamically using Java Reflection API ?.

Program to demonstrate how to determine Interfaces implemented by a class dynamically using Java Reflection API.

package com.hubberspot.reflection;


// Created two three interfaces just for the demo
// such as Shape, Rotation and Movable
interface Shape
{

}

interface Rotation 
{

}

interface Movable
{

}

// Created a class which implements all those interfaces
class Circle implements Shape , Rotation , Movable 
{

}


public class InterfacesFinding {

 public static void main(String[] args) {

  // Get the instance of Class of the type Circle 
  Class classCircle = Circle.class;

  // class Class defines a method which returns
  // an array of interfaces 
  Class[] interfacesArray = classCircle.getInterfaces();

  System.out.println("Interfaces implemented by Circle class are : ");

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

   String interfaceName = interfacesArray[i].getName();

   System.out.println(i + 1 + " " +interfaceName);
  }

 }

}


Output of the program : 


 

How to find Superclasses of a given class dynamically using Java Reflection API ?.

Program to demonstrate how to find Superclasses of a given class dynamically using Java Reflection API.

package com.hubberspot.reflection;

// Create Three Java classes such as 
// Animal which extends Object

class Animal 
{

}

//Dog which extends Animal
class Dog extends Animal 
{

}

// GermanShepherd which extends Dog
class GermanShepherd extends Dog
{

}


public class SuperClassFinding {

 public static void main(String[] args) {

  // Get the instance of Class for the type 
  // GermanShepherd
  Class childClass = GermanShepherd.class;

  // Get the instance of Class for the supertype
  // of the class GermanShepherd. The Class instance 
  // for super-class is been found by calling 
  // getSuperclass() method of class Class.
  Class superClass = childClass.getSuperclass();

  // Loops over the hierarchy of classes in examples
  // till reaching the top most class Object
  while(superClass != null)
  {

   // In order to get name of the superclass
   // we call method getName over the Class instance
   // of Superclass
   String className = superClass.getName();

   // Prints over the console
   System.out.println("The Super Class for " + 
     childClass.getName() + " is : \n" + className);

   childClass = superClass;

   superClass = childClass.getSuperclass();

   System.out.println();

  }

 }

}



Output of the program :



How to determine class modifiers dynamically using Java Reflection API ?.

Program to demonstrate how to determine class modifiers dynamically using Java Reflection API

package com.hubberspot.reflection;

import java.lang.reflect.Modifier;

// Create classes with different modifiers as
// final, abstract, public etc
abstract class Animal
{

}

public final class Dog extends Animal {

 public static void main(String[] args) {

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

  // Get the instance of Class as Dog.class
  Class classDog = Dog.class;

  // Class class has a method called as  getModifiers(). 
  // This method Returns the Java language modifiers for 
  // the class as a integer. The modifiers consist of the 
  // Java Virtual Machine's constants for public, protected, 
  // private, final, static, abstract and interface; 
  // they should be decoded using the methods of class Modifier.  
  int modifier = classDog.getModifiers();

  // Modifier class has many static methods such as isPublic , 
  // isPrivate, isStatic, isFinal, isAbstract etc. These methods
  // returns back a boolean value checking whether given argument to 
  // method is of particular modifier
  // See below for the demo ... 
  if(Modifier.isPublic(modifier))
  {
   System.out.println("Class Dog is declared as:  public");
  }

  if(Modifier.isFinal(modifier))
  {
   System.out.println("Class Dog is declared as:  final");
  }

  if(!Modifier.isStatic(modifier))
  {
   System.out.println("Class Dog is not declared as:  static");
  }

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

  Class classAnimal = Animal.class;

  modifier = classAnimal.getModifiers();

  if(Modifier.isAbstract(modifier))
  {
   System.out.println("Class Animal is declared as:  abstract");
  }

  if(!Modifier.isFinal(modifier))
  {
   System.out.println("Class Animal is not declared as:  final");
  }

  if(!Modifier.isStatic(modifier))
  {
   System.out.println("Class Animal is not declared as:  static");
  }

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





Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot