Sometimes I need to display a POJO’s properties/attributes. These POJOs may contain dozens of properties making it tedious to invoke all the
In the following example, the
getXxx() methods. So Java Reflection is a perfect candidate for such a use case.In the following example, the
LoginResponse class contains dozens of fields that I want to display. The formatMethodName() method beautifies the getXxx() method names into more human user friendly names.
import java.lang.reflect.Method;
import com.laws.acc.ws.*;
import com.laws.acc.model.*;
LoginResponse loginResponse=AccSoapClientProxy.getLoginResponse();
void populateRows() {
if(loginResponse!=null) {
Method[] methods = LoginResponse.class.getDeclaredMethods();
for(int i=0; i<methods.length; i++) {
Method method=methods[i];
//Object arglist[]={};
if(method.getName().startsWith("get")) {
Row row=new Row();
Label label=new Label(formatMethodName(method.getName()));
label.setStyle("font-style: italic;");
label.setParent(row);
new Label(method.invoke(loginResponse, null).toString()).setParent(row);
row.setParent(rows);
}
}
}
}
/**
* turn strings such as 'getUserName' into 'User Name'
*/
private String formatMethodName(String name) {
// the method name should start with 'get' followed by the property name
// otherwise, ignore the method.
if(name==null || name.length()<4) return null;
StringBuffer sb=new StringBuffer();
// skip the first 3 characters, they are 'get'
for(int i=3; i<name.length(); i++) {
char ch = name.charAt(i);
if(i>3 && ch>='A' && ch<='Z') {
sb.append(" ");
}
sb.append(ch);
}
return sb.toString().replace("Id", "ID").replace("Dt", "Timestamp").replace("Lre", "LRE").replace("Mvno", "MVNO");
}
The GUI component I am using is a ZK Grid with each row showing a property value.
// put the above java code here. populateRows();

No comments:
Post a Comment