Please disable adblock to view this page.

← Go home

Run Time Type Information snippet (RTTI – Java)

May 10, 2016
Published By : Pratik Kataria
Categorised in:

Code

//************************* Manager.java *************************

public class Manager extends Employee {

	public Manager(int empId, String empName) {
		super(empId, empName);
	}
	
	public void salary(){}
	public void bonus(){}

}

//************************* Employee.java *************************

public class Employee {

	//Run Time Type Info
	
	int empId;
	String empName;
	
	public Employee(int empId, String empName) {
	
		this.empId = empId;
		this.empName = empName;
		
	}
	public void fun(){}
	public void test(){}
	
	@Override
	public String toString() {
		
		return "ID: " + empId + "    Employee Name: "+empName ;
	}
	
}

//************************* Main.java *************************

import java.lang.reflect.Method;

public class Main {

	public static void main(String[] args) {
		
		Employee employee1 = new Employee(111, "Patrick");
		System.out.println(employee1);
		Employee employee2 = new Employee(112, "Pratik");
		System.out.println(employee2);
		
		//RTTI
		Class myClass; 	//This is provided by java
		myClass = employee1.getClass();	//This stores the reference's classname
		System.out.println("Class Name: " + myClass.getClass().getName());
		System.out.println("--------------------------");
		System.out.println("Now we change reference of employee");
		System.out.println("--------------------------");
		
		Employee employee = new Manager(113, "Code");
		myClass = employee.getClass();
		System.out.println("Class Name: " + myClass.getClass().getName());
		System.out.println("Super Class Name: " + myClass.getSuperclass().getName());

		//Now for printing methods name
		
		Method[] methods = employee.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			System.out.println("Method Name: " + methods[i].getName());
		}
		
	
	}
	
}

Output:

ID: 111 Employee Name: Patrick
ID: 112 Employee Name: Pratik
Class Name: java.lang.Class
————————–
Now we change reference of employee
————————–
Class Name: java.lang.Class
Super Class Name: Employee
Method Name: salary
Method Name: bonus
Method Name: toString
Method Name: test
Method Name: fun
Method Name: wait
Method Name: wait
Method Name: wait
Method Name: equals
Method Name: hashCode
Method Name: getClass
Method Name: notify
Method Name: notifyAll

View Article Page
Download