Consider the following code : (an Employee is a Person who has an empID)
public class Person {
private String name;
public Person() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Employee extends Person {
private String empID;
public Employee() {
super();
}
public String getEmpID() {
return empID;
}
public void setEmpID(String id) {
empID = id;
}
}
Both JSP's standard actions getParameter and setParameter use introspection to find the getter/setter of a property, so accessing the following page displays the employee's id correctly, even if the bean is a Person:
http://localhost:8080/jspaction/getter.jsp?name=doraemon&empID=12345
<jsp:useBean id="per" type="bean.Person" class="bean.Employee" scope = "page">
<jsp:setProperty name="per" property = "*"/>
</jsp:useBean>
Person Name:<jsp:getProperty name="per" property="name"/>
Employee ID:<jsp:getProperty name="per" property="empID"/>
The following code illustrates what introspection is :
public class Reflection {
public static void main(String[] args) {
Person per = new Employee();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(per.getClass());
MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
for ( int i = 0; i < methodDescriptors.length; i++ ) {
Method method = methodDescriptors[i].getMethod();
System.out.println("Method : " + method.getName() );
}
} catch ( IntrospectionException e ) {
e.printStackTrace();
}
Method[] methods = per.getClass().getMethods();
for ( int i = 0; i < methods.length; i++ ) {
System.out.println("ClassMethod : " + methods[i].getName() );
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor("empID", per.getClass());
Method getter = descriptor.getReadMethod();
Method setter = descriptor.getWriteMethod();
System.out.println("Getter: " + getter.getName() + " Setter: " + setter.getName());
} catch( IntrospectionException e ) {
e.printStackTrace();
}
}
}
Refer also to the following thread :
Bryan Basham about setProperty