- Reflection is used to analyse a class at runtime.
- It is used to get the structure of a class at run time.
- Through reflection we are able to retrieve the information like constructors, fields and methods associated with the class.
- Reflection is used to change the values of data fields in objects.
For example consider the class 'Person'
package com.java;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int age;
}
Reflection class
package com.java;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// Creates an object of type Class which contains the information of
// the class String
Class cl = Class.forName("com.java.Person");
// getDeclaredFields() returns all the constructors of the class.
Constructor cnst[] = cl.getConstructors();
// getFields() returns all the declared fields of the class.
Field fld[] = cl.getDeclaredFields();
// getMethods() returns all the declared methods of the class.
Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class");
for (int i = 0; i < cnst.length; i++) {
System.out.println(cnst[i].getName().toString());
}
System.out.println("Name of the Declared fields");
for (int i = 0; i < fld.length; i++) {
System.out.println(fld[i].getName().toString());
}
System.out.println("Name of the Methods");
for (int i = 0; i < mtd.length; i++) {
System.out.println(mtd[i].getName().toString());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Result
Name of the Constructors of the String class
com.java.Person
Name of the Declared fields
name
age
Name of the Methods
getAge
setAge
getName
setName
wait
wait
wait
hashCode
getClass
equals
toString
notify
notifyAll
Reflection in java
Madhu Tomy is a passionate programmer who has been programming with Java since the time of Java 1.4 (15 years ago). He is a certified Java programmer with SCJP (Sun Certified Java Programmer). . The blog posts are from my own experiences in dealing with various issues during web development. I take a lot from the web community and in turn share back my contributions through my BLOG. Other favorites include Movies, Listening to Songs.
Subscribe to:
Post Comments (Atom)
Python Basics How to check the version of Python interpreter mac terminal
Popular in last 30 days
-
Element 'dependency' cannot have character [children], because the type's content type is element-only in pom.xml Solution: ...
-
Hibernate Unknown integral data type for ids When starting my spring boot application @Entity public class PlugMillingData { p...
-
Textpad is one of the most useful editor tools. 1. Open the Textpad 2. Go to Tools --> Sort 3. Check the box corresponding to the opt...
No comments:
Post a Comment