Lab

Laboratory For Innovators

Rss

Java – Reflection Tutorial

Here i provide java reflection tutorial

This tutorial divide into two part

1) Quick Guide (QuickMain.java)
2) Detail Guide (DetailMain.java)

Create project structure as show in above image.Create project with name omtReflection,then create two packages :
1) com.omt.classes
2) com.omt.main

Now create two (Cars.java) and (Vehicle.java) class in com.omt.classes and copy below code in it.

1) Cars.java
Copy below code in Cars.java

package com.omt.classes;
public class Cars {

	public Cars() {
	
	}
	
	public void aboutCars()
	{
		System.out.println("This is all about cars.");
	}
	
}

2) Vehicle.java
Copy below code in Vehicle.java

package com.omt.classes;

public class Vehicle {

	
	//All Fields
	
	private String name = "";
	public int price = 0;
	protected String about = "";
	public String companyName = "";
	
	//All Constructor 
	
	public Vehicle() {
	  System.out.println("Vehicle()");
	}	
	
	public Vehicle(String vName) {
		this.name = vName;
		System.out.println("Vehicle(String vName) :"+vName);
	}
	
	public Vehicle(String carName,int price) {
		this.name = carName;
		this.price = price;
		System.out.println("Vehicle(String carName,int price)"+carName+","+price);
	}
	
	
	// All Methods 
	
	public void setName(String name,int price)
	{
		this.name = name;
		this.price = price;
		System.out.println("Name and Price is Set :::>>"+name+" and "+price);
	}
	
	public void setCompanyName(String cname)
	{
		this.companyName = cname;
		System.out.println("Company Name is Set :>>"+companyName);
	}
	
	public int getPrice()
	{
		return price;
	}
	
	
	
	public void printDetails()
	{
		System.out.println("Vehicle Name :"+name);
		System.out.println("Vehicle Price :"+price);
		System.out.println("Vehicle about :"+about);
		System.out.println("Vehicle CompanyName :"+companyName);
	}
	
}

Now create two (QuickMain.java) and (DetailMain.java) class in com.omt.main package

1) QuickMain.java
Copy below code in QuickMain.java

 
package com.omt.main;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class QuickMain {

	public static void main(String[] args) {
		
      try {
		Class c = Class.forName("com.omt.classes.Cars");
		Method m[] = c.getDeclaredMethods();
		Object carObj = null;
		carObj = c.newInstance();
		
		int size = m.length;
		
		for(int i = 0 ; i < size ; i++)
		{
			System.out.println("Class Name : "+c.getSimpleName()+" and Method Name :"+m[i]);
			Method  callM = m[i];			
			callM.invoke(carObj, null);			
		}
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	}

}

2) DetailMain.java
Copy below code in DetailMain.java

 
package com.omt.main;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.omt.classes.Vehicle;

public class DetailMain {

	public static void main(String args[])
	{
		System.out.println("getMethodNames------------------------------------------------------\n");
		getMethodNames();
		System.out.println("getConstructorNames--------------------------------------------------------------------\n");
		getConstructorNames();
		System.out.println("getFieldNames--------------------------------------------------------------------\n");
		getFieldNames();
		System.out.println("invokeMethodsAndVariables--------------------------------------------------------------------\n");
		invokeMethodsAndVariables();
		System.out.println("createObjectUseingConstructors--------------------------------------------------------------------\n");
		createObjectUseingConstructors();
	}
	
	 
	public static void getMethodNames()
	{
		try{
		     Class c = Class.forName("com.omt.classes.Vehicle");
		     System.out.println("Class Name :"+c.getName()+"\n");
		     Method allMethodsArray[] = c.getDeclaredMethods();
		     int size = allMethodsArray.length;
		     for(int i = 0 ; i < size ; i++)
		     {
		    	System.out.println("Methods ( "+i+" ) :"+allMethodsArray[i]); 
		     }     
		    	 
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static void getConstructorNames()
	{
		try{
             Class c = Class.forName("com.omt.classes.Vehicle");
             System.out.println("Class Name :"+c.getName()+"\n");
             Constructor allConstructorArray[] = c.getDeclaredConstructors();
             
             int size = allConstructorArray.length;
             for(int i = 0 ; i < size ; i++)
		     {
		    	System.out.println("Constructor ( "+i+" ) :"+allConstructorArray[i]); 
		     }  
		}catch (Exception e) {
            e.printStackTrace();
		}
	}
	
	public static void getFieldNames()
	{
		try{
            Class c = Class.forName("com.omt.classes.Vehicle");
            System.out.println("Class Name :"+c.getName()+"\n");
            Field allFieldArray[] = c.getDeclaredFields();
            
            int size = allFieldArray.length;
            for(int i = 0 ; i < size ; i++)
		     {
		    	System.out.println("Field ( "+i+" ) :"+allFieldArray[i]); 
		     }  
		}catch (Exception e) {
           e.printStackTrace();
		}
	}
	
	public static void invokeMethodsAndVariables()
	{
		try{
            Class c = Class.forName("com.omt.classes.Vehicle");
            System.out.println("Class Name :"+c.getName()+"\n");
            
            //Create Object of class
            //This is same as ::: Vehicle v = new Vehicle();            
            Object o = c.newInstance();            
            
            // ALL FIELD RELATED STUFF ----START    
            //Here i demonstrate how to assign value to field using reflection 
            Field allFieldArray[] = c.getDeclaredFields();                        
            int size = allFieldArray.length;
            for(int i = 0 ; i < size ; i++)
		    {
		    	System.out.println("Field ( "+i+" ) :"+allFieldArray[i]);
		    	Field f = allFieldArray[i];
		    	Class<?> type = f.getType();
		    	//Here we identify type of field
		    	if(type.isInstance(new String()))
		    	{
		    		//Here we set value of field 
		    		System.out.println(""+f.getName()+" :is Type String ");
		    		
		    		//Only Public Member can be access here 
		    		//We can not access private or protected member of class, Here name is private so we can not access it
		    		if(f.toString().indexOf("private") == -1 && f.toString().indexOf("protected") == -1)
		    		{
		    		  f.set(o, "This is :"+f.getName());
		    		}else
		    		{
		    			System.out.println(f.getName()+" is private or protected member");
		    		}
		    		
		    	}else
		    	if(type.toString().equals("int"))
		    	{
		    		System.out.println(""+f.getName()+" :is Type Integer ");
		    		f.set(o, 1);
		    	}
		    }
         // ALL FIELD RELATED STUFF ----END
         
         // ALL METHODS RELATED STUFF ----START
          //Here i demonstrate how to pass parameter and call methods
            Method allMethodArray[] = c.getDeclaredMethods();
            size = allMethodArray.length;
            for(int i = 0 ; i < size ; i++)
		     {
		    	System.out.println("Methods ( "+i+" ) :"+allMethodArray[i]); 
		    	Method m = allMethodArray[i];
		    	Class<?> parameterArray[] = m.getParameterTypes();
		    	Object parameterToPass[] = new Object[parameterArray.length];
		    	
		    	for(int j = 0 ; j < parameterArray.length ; j++)
		    	{
		    		if(parameterArray[j].isInstance(new String()))
		    		{
		    			parameterToPass[j] = "Passing String in Param For Method:"+m.getName();
		    		}else
		    		if(parameterArray[j].toString().equals("int"))
		    		{
		    			parameterToPass[j] = 78;
		    		}		    			
		    	}
		        Object returnValue = m.invoke(o, parameterToPass);
		        
		        System.out.println("***********RETURN_VALUE:"+returnValue);
		     }                 
         //ALL METHODS RELATED STUFF ----END
            
            
		}catch (Exception e) {
           e.printStackTrace();
		}
	}
	
	public static void createObjectUseingConstructors()
	{
		try{
            Class c = Class.forName("com.omt.classes.Vehicle");
            System.out.println("Class Name :"+c.getName()+"\n");
            Constructor allConstructorArray[] = c.getDeclaredConstructors();
            
            int size = allConstructorArray.length;
            for(int i = 0 ; i < size ; i++)
		     {
		    	System.out.println("Constructor ( "+i+" ) :"+allConstructorArray[i]); 
		    	Constructor constructor = allConstructorArray[i];
		    	Class<?> parameterArray[] = constructor.getParameterTypes();
                Object parameterToPass[] = new Object[parameterArray.length];
            	for(int j = 0 ; j < parameterArray.length ; j++)
		    	{
		    		if(parameterArray[j].isInstance(new String()))
		    		{
		    			parameterToPass[j] = "Passing String in Constructor";
		    		}else
		    		if(parameterArray[j].toString().equals("int"))
		    		{
		    			parameterToPass[j] = 88;
		    		}		    			
		    	}
            	Object o = constructor.newInstance(parameterToPass);
		     }  
		}catch (Exception e) {
           e.printStackTrace();
		}
	}
	
}

Output of QuickMain.java
Class Name : Cars and Method Name :public void com.omt.classes.Cars.aboutCars()
This is all about cars.

Output of DetailMain.java
getMethodNames——————————————————

Class Name :com.omt.classes.Vehicle

Methods ( 0 ) :public void com.omt.classes.Vehicle.setName(java.lang.String,int)
Methods ( 1 ) :public void com.omt.classes.Vehicle.setCompanyName(java.lang.String)
Methods ( 2 ) :public int com.omt.classes.Vehicle.getPrice()
Methods ( 3 ) :public void com.omt.classes.Vehicle.printDetails()
getConstructorNames——————————————————————–

Class Name :com.omt.classes.Vehicle

Constructor ( 0 ) :public com.omt.classes.Vehicle()
Constructor ( 1 ) :public com.omt.classes.Vehicle(java.lang.String)
Constructor ( 2 ) :public com.omt.classes.Vehicle(java.lang.String,int)
getFieldNames——————————————————————–

Class Name :com.omt.classes.Vehicle

Field ( 0 ) :private java.lang.String com.omt.classes.Vehicle.name
Field ( 1 ) :public int com.omt.classes.Vehicle.price
Field ( 2 ) :protected java.lang.String com.omt.classes.Vehicle.about
Field ( 3 ) :public java.lang.String com.omt.classes.Vehicle.companyName
invokeMethodsAndVariables——————————————————————–

Class Name :com.omt.classes.Vehicle

Vehicle()
Field ( 0 ) :private java.lang.String com.omt.classes.Vehicle.name
name :is Type String
name is private or protected member
Field ( 1 ) :public int com.omt.classes.Vehicle.price
price :is Type Integer
Field ( 2 ) :protected java.lang.String com.omt.classes.Vehicle.about
about :is Type String
about is private or protected member
Field ( 3 ) :public java.lang.String com.omt.classes.Vehicle.companyName
companyName :is Type String
Methods ( 0 ) :public void com.omt.classes.Vehicle.setName(java.lang.String,int)
Name and Price is Set :::>>Passing String in Param For Method:setName and 78
***********RETURN_VALUE:null
Methods ( 1 ) :public void com.omt.classes.Vehicle.setCompanyName(java.lang.String)
Company Name is Set :>>Passing String in Param For Method:setCompanyName
***********RETURN_VALUE:null
Methods ( 2 ) :public int com.omt.classes.Vehicle.getPrice()
***********RETURN_VALUE:78
Methods ( 3 ) :public void com.omt.classes.Vehicle.printDetails()
Vehicle Name : Passing String in Param For Method:setName
Vehicle Price :78
Vehicle about :
Vehicle CompanyName : Passing String in Param For Method:setCompanyName
***********RETURN_VALUE:null
createObjectUseingConstructors——————————————————————–

Class Name :com.omt.classes.Vehicle

Constructor ( 0 ) :public com.omt.classes.Vehicle()
Vehicle()
Constructor ( 1 ) :public com.omt.classes.Vehicle(java.lang.String)
Vehicle(String vName) : Passing String in Constructor
Constructor ( 2 ) :public com.omt.classes.Vehicle(java.lang.String,int)
Vehicle(String carName,int price)Passing String in Constructor,88

Share

Comments are currently closed.