Reflection in java

  • This API helps to inspect classes, interfaces, field and methods at runtime.
  • It is java API- Reflection
#we can use it for
  • Analyze the capabilities of classes at runtime;
  • Inspect objects at runtime, for example, to write a single toString method that works for all classes;
  • Implement generic array manipulation code; and
  • Take advantage of Method objects that work just like function pointers in languages such as C++.
#Some basics
  • Class class
  • Class c1=e.getClass(); if e is an object of type Employee
  • Date d = new Date(); Class cl = d.getClass(); //It will results java.util.Date
  • e.getClass().newInstance(); helps to create new instance of type Employee
#Using Reflection to Analyze the Capabilities of Classes
  • The three classes Field, Method, and Constructor in the java.lang.reflect package describe the fields, methods, and constructors of a class.
  • all three classes have getName() method will return name of the item,
  • Filed-> getType() will return the type of the filed.
  • there have methods for Method class to get the number of modifiers, return type and modifiers
  • for constructor-> getModifiers(), getDeclaringClass() are among them
# Using Reflection to Analyze Objects at Runtime
  • Employee harry = new Employee("Harry Hacker", 35000, 10, 1, 1989);
Class cl = harry.getClass();
// the class object representing Employee
Field f = cl.getDeclaredField("name");
// the name field of the Employee class
Object v = f.get(harry);
// the value of the name field of the harry object
// i.e., the String object "Harry Hacker"
  • f.setAccessible(true); //if the field is private w can access by calling this.

Comments