JAVA Reflection API - An Example to invoke fields
Assume that we have 50 Java Bean classes with each class having atleast 5 fields with getter/setter methods. Now its time for you to debug the contents of each object.
So how do we have to debug all these classes?
- Implement a toString() method inside each class.
- Create a StringBuilder/StringBuffer object inside the toString() method.
- Append each and every field present inside the class to buider/buffer object in the toString() method, and
then return this object by converting it into a String.
- This process translates the object into a well-defined understandable textual format.
Well, this is really a good process, but, keeping in mind that we have tens of classes resulting in hundreds of variables, how long do you think it'd take to debug all our classes. I bet this process sucks big time
So,What is the alternative????
Lets get into programming for a while.
Class-1: RootObject.java
Class-2: Role.java
Class-3: User.java
Class-4: InvokeFields.java [Main Class]
Watch the programs carefully and think of the output. The following is the output that we get when we execute the main class, InvokeFields.java.
This is just a small example used to invoke the fields during runtime. I am able to print all the contents of the User object even without overriding the toString() method inside that class. [The toString() mechanism in fact is present in the super class of User object.]
How was that possible?
Its the Java Reflection API which helped us in printing all the values dynamically.
The toString() method implementation in the BaseObj.java class is responsible for
printing all the values present in User.java and Role.java classes.
To avoid performance overheads, use this approach only for debugging.
So how do we have to debug all these classes?
- Implement a toString() method inside each class.
- Create a StringBuilder/StringBuffer object inside the toString() method.
- Append each and every field present inside the class to buider/buffer object in the toString() method, and
then return this object by converting it into a String.
- This process translates the object into a well-defined understandable textual format.
Well, this is really a good process, but, keeping in mind that we have tens of classes resulting in hundreds of variables, how long do you think it'd take to debug all our classes. I bet this process sucks big time
So,What is the alternative????
Lets get into programming for a while.
Class-1: RootObject.java
package com.devonline.reflec.samples; import java.io.Serializable; import java.lang.reflect.Field; public class RootObject implements Serializable { public String toString() { StringBuilder returnString = new StringBuilder(); Class clazz = this.getClass(); Field[] fields = clazz.getDeclaredFields(); try { for (Field field : fields) { field.setAccessible(true); StringBuilder attributeValue = new StringBuilder(); attributeValue.append(" " + field.getName() + " : "); attributeValue .append((field.get(this) == null) ? null : field.get(this).toString()); returnString.append(attributeValue.toString() + "\n"); } } catch (Exception e) { e.printStackTrace(); } return "\n" + clazz.getSimpleName() + " {\n" + returnString.toString() + " }\n"; } }
Class-2: Role.java
package com.devonline.reflec.samples; public class Role extends RootObject { private int roleId; private String roleName; private boolean isActive; public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } }
Class-3: User.java
package com.devonline.reflec.samples; import java.util.Date; import java.util.List; public class User extends RootObject { private String userId; private String status; private String firstName; private String lastName; private String emailId; private String updatedBy; private Date updatedOn; private List<Role> roles; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedOn() { return updatedOn; } public void setUpdatedOn(Date updatedOn) { this.updatedOn = updatedOn; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } }
Class-4: InvokeFields.java [Main Class]
package com.devonline.reflec.samples; import java.util.ArrayList; import java.util.Date; import java.util.List; public class InvokeFields { public static void main(String args[]) { InvokeFields invokeFields = new InvokeFields(); User user = invokeFields.getUser(); System.out.println(user); } private Role getGuestRole() { Role role = new Role(); role.setRoleId(2); role.setRoleName("Guest"); role.setActive(false); return role; } private Role getGreenHornRole() { Role role = new Role(); role.setRoleId(3); role.setRoleName("Greenhorn"); role.setActive(true); return role; } private User getUser() { User user = new User(); List<Role> roles = new ArrayList<Role>(); roles.add(getGuestRole()); roles.add(getGreenHornRole()); user.setUserId("JU001"); user.setFirstName("Java"); user.setLastName("User"); user.setEmailId("javauser@test.com"); user.setStatus("Y"); user.setUpdatedBy("Admin"); user.setUpdatedOn(new Date()); user.setRoles(roles); return user; } }
Watch the programs carefully and think of the output. The following is the output that we get when we execute the main class, InvokeFields.java.
This is just a small example used to invoke the fields during runtime. I am able to print all the contents of the User object even without overriding the toString() method inside that class. [The toString() mechanism in fact is present in the super class of User object.]
How was that possible?
Its the Java Reflection API which helped us in printing all the values dynamically.
The toString() method implementation in the BaseObj.java class is responsible for
printing all the values present in User.java and Role.java classes.
To avoid performance overheads, use this approach only for debugging.
Comments
Post a Comment