C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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;
	public Computer(String MacNo,int productId,long 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);

		/////// Now We Will Access productId Let Us See......
			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
			int pid=(int)F1.get(C);
			Field F2=plsc.getDeclaredField("MacNo");
			String MacNo=(String)F2.get(C);
			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)


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.

Liked this article? Do share with your friends :)

Are you a blogger? Join our Blogging forum.