<aside> 💡 Reflective programming or Reflection is the ability of a process to examine, introspect, and modify its structure and behaviour.
</aside>
Given a code below:
Employee e = new Manager(...);
...
if (e instanceof Manager){
...
}
Problem: What if we don’t know the type that we want to check in advance?
Solution: Use getClass()
to extract the class of an object.
java.lang.reflect
import java.lang.reflect.*;
class MyReflectionClass{
...
public static boolean(Object o1, Object o2){
return (o1.getClass() == o2.getClass())
}
}
getClass()
method
Class
that encodes class information.Class
Here is a code that explicitly uses the type Class
to compare two classes.
import java.lang.reflect.*;
class MyReflectionClass{
...
public static boolean classequal(Object o1, Object o2){
Class c1, c2;
c1 = o1.getClass();
c2 = o2.getClass();
return (o1==o2);
}
}
For each currently loaded class C
,Java creates an object of type Class
with information about C
<aside> 💡 Encoding execution state as data is called Reification.
</aside>
Representing an abstract idea in a concrete form.
Class
objectCan create new instances of a class at runtime.
....
Class c = obj.getClass();
Object o = c.newInstance();
//This will create an object o of same type as that of obj.
....
Can get hold of the class object using the name of the class.
...
String s = "Manager";
Class c = Class.forName(s);
Object o =c.newInstance();
...
Write more compactly as:
Object o = Class.forName("Manager").newInstance()
Class
object for class C
, we can extract details about constructors, methods and fields of C
Structure of these entities:
Additional classes Constructor
, Method
, Field
Use getConstructors()
, getMethods()
, getFields()
to obtain constructors , methods , and fields of C
in an array.
Extracting information about constructors , methods, fields.
...
Class c = obj.getClass();
Constructor[] constructors = c.getConstructors();
Method[] methods = c.getMethods();
Fields[] fields = c.getFields();
...
Now, Constructors, Method, Field in turn have functions to get further details.