Home » Java programming language

Java Reflection API to change the behavior of the class

In this article, we are going to learn how we can change the behavior of a class methods or fields during runtime that is how you can access a private member of a class by changing its behavior from private to accessible.
Submitted by Jyoti Singh, on February 27, 2018

JavaReflection API provides methods to change the behavior of a class. Let’s understand this by an example.

class Product{
	private string name;
	public int price;
}

Here, if we can access price data member of the class as it is public but we cannot access name data member as it is private. In order to do this we have to use a javaReflectionAPI method setAccessible(true). This method change the behavior of a data member, takes a boolean parameter that is true or false if it is set to true then that data member will become accessible.

Let’s implement this in our program:

import  java.lang.reflect.Field;

//a class representing computer
class Computer
{
	private String MacNo;
	//We Will change the private behavior Of 
	//this member At Runtime Through Java Reflection API
	private int productId;   
	public long price;
	
	//constructor
	public Computer(String MacNo,int productId,long price)
	{
		this.MacNo=MacNo;	
		this.productId=productId;
		this.price=price;
	}
	//to string function to show the data object values
	public String toString()
	{
		return("Mac Number :"+this.MacNo+"\nProductId :"+this.productId+"\nPrice :"+this.price);	
	}
}

//main class 
public class ExChangIngTheBehaviorOfClassAtRunTime_JAVAREFLECTION_API {
	public static void main(String[] args) {
		Computer C=new Computer("MDSK89*$",100,29000);
		System.out.println(C);

		/////// Now We Will Access productId Let Us See......
		try 
		{
			Class plsc=Class.forName("logicProgramming.Computer");
			
			// getDeclaredField returns the specified field of the class
			Field F1=plsc.getDeclaredField("productId");
			
			// stting the accessibility to true so that we can access fields
			F1.setAccessible(true);
			int pid=(int)F1.get(C);
			Field F2=plsc.getDeclaredField("MacNo");
			F2.setAccessible(true);
			String MacNo=(String)F2.get(C);
			System.out.println();
			System.out.println("MacNumber :"+MacNo+"\nProductId :"+pid+"\nPrice :"+C.price);
			//Hey We Are Able To Access Private Members 
			//Of Class Computer Mac Number and Product Id     
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}

Output

Java Reflection API to change the behavior of the class

Here, we are able to access the fields that were private in the above class.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.