Java Reflection What is Reflection Reflection is the
- Slides: 12
Java Reflection
What is Reflection “Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. ”
Class Object q. The class object reflects the class it represents. q. Instances of class stores information about classes: Class name q Inheritance q Interfaces implemented q Methods and fields q
Accessing the class object q Class c 1 =Class. for. Name(“java. util. Properties”); q Class c 2 = obj. get. Class(); q Fields[] fields = c. get. Fields(); q Method[] methods = c. get. Methods(); q Class[] interaces = c. get. Interfaces();
Example public class Class. Demo { public static void main(String args[]){ String s=new String(); Class c=s. get. Class(); System. out. println(c. get. Name()); System. out. println(c. get. Superclass()); } java. lang. String } class java. lang. Object
Main Java Reflection Classes Class(java. lang. class) Instances of the class Classrepresent classes and interfaces in a running Java application, every object is represented by a Class object Package java. lang. reflect
java. lang. reflect -Member(java. lang. reflect. Member ) • An Interface that reflects identifying information about a single member (a field or a method) or a constructor. –Method(java. lang. reflect. Method ) • Implements Member Interface • final class • Represents instance methods and class methods ( static ).
Example import java. lang. reflect. Method; public class Member. Demo { public static void main(String args[]) { String s=new String(); Class c=s. get. Class(); Method m[]=c. get. Methods(); for(int i=0; i<m. length; i++){ System. out. println(m[i]); } }}
java. lang. reflect Field(java. lang. reflect. Field) –Implements Member Interface –provides information about a field ( also for static fields ) – final class • Constructor(java. lang. reflect. Constructor) –provides information about, and access to, a single constructor for a class. –Implements Member Interface –final class
Example import java. lang. reflect. Field; public class Field. Demo { public static void main(String args[]) { Thread t=new Thread(); Class c=t. get. Class(); Field f[]=c. get. Fields(); for(int i=0; i<f. length; i++){ System. out. println(f[i]); } } } public static final int java. lang. Thread. MIN_PRIOR public static final int java. lang. Thread. NORM_PRIO
Example import java. lang. reflect. Constructor; public class Constructor. Demo { public static void main(String args[]) { String s=new String(); Class c=s. get. Class(); Constructor c 1[]=c. get. Constructors(); for(int i=0; i<c 1. length; i++){ System. out. println(c 1[i]); } }}
Example public class Interface. Demo { public static void main(String args[]){ Class c=new String(). get. Class(); Class in[]=c. get. Interfaces(); for(int i=0; i<in. length; i++) System. out. println(in[i]); }} interface java. io. Serializable interface java. lang. Comparable