Run Time Type Information snippet (RTTI – Java)
May 10, 2016
Categorised in: Java Codes
//************************* 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
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.