Friday, September 14, 2007

the describe method of the DataObjects...

Joy ho!

I written and tested a Java code recently... (yes, it works :-) )
Its a generic describe method for Data Objects which uses reflect API provided in Java.
This works even if you have a hierarchy of Data Objects.

Here is the code:

// Yeeeah! a code by UJ... the PowerBuilder.
public String describe()
{
// Output Format: ClassName [field1 = value1, field2 = value2, ...]
try
{
StringBuffer sbReturn = new StringBuffer();
// get the associated 'Class' object
Class theClass = this.getClass();

// appending the classname
sbReturn.append(theClass.getName().substring(theClass.getName().lastIndexOf(".")+1));
sbReturn.append(" [");

// Exclude the Object class...
while(theClass.getSuperclass() != null)
{
// Get all methods
Method methods[] = theClass.getDeclaredMethods();
for(int i=0; i
{
String methodName = methods[i].getName();
// if its a getter method...
if(methodName.startsWith("get"))
{
// get the field name
sbReturn.append(methodName.substring(3));
sbReturn.append(" = ");
// get value by invoking getter method
sbReturn.append(String.valueOf(methods[i].invoke(this, new Object[0])));
sbReturn.append(", ");
}
}
// get the parent class
theClass = theClass.getSuperclass();
}
// finally, remove the last comma & space appended
sbReturn.setLength(sbReturn.length() - 2);
// done.
sbReturn.append("]");
return sbReturn.toString();
}
catch(Exception ex)
{
return null;
}
}


And here is the sample output:

SpecDetailFormGateway [P4Path = xyz, P4Changelist = null, DataFormat = edi, DataFormatVersion = null, StrAction = null, SpecID = null, Editable = true, XPath = null, StrDetailType = GATEWAY, StrProductName = null, StrLECName = null, StrVersionID = null, GatewayName = ASR, Comments = Animesh, Servlet = null, MultipartRequestHandler = null]


knowledge shared is knowledge squared.
~ Jariya

PS: make sure to import java.lang.reflect.Method