Monday, October 13, 2008

Reflection in Java

Creating a object using reflection in Java:

Class parserClass=Class.forName(parser);
Object newParser=parserClass.newInstance();
Class classParams[]=new Class[1]; //To set type of parameter
Object arglist[]=new Object[1]; //To set the actual value

classParams[0] = String.class;
arglist[0] = tradeType;
String methodName="setLoadType";

Method meth = parserClass.getMethod(methodName, classParams);

meth.invoke(newParser, arglist); //Set setTradeType=tradeType

return (DefaultFileParser)newParser;


StringArrayConvertor in Java

public Object convert(Class type,
Object value)
Deprecated.
Convert the specified input object into an output object of the specified type.
If the value is already of type String[] then it is simply returned unaltered.
If the value is of type int[], then a String[] is returned where each element in the string array is the result of calling Integer.toString on the corresponding element of the int array. This was added as a result of bugzilla request #18297 though there is not complete agreement that this feature should have been added.
In all other cases, this method calls toString on the input object, then assumes the result is a comma-separated list of values. The values are split apart into the individual items and returned as the elements of an array. See class AbstractArrayConverter for the exact input formats supported.
Converting Strng Array to String in Java
public static String arrayToString(String[] a, String separator) {
StringBuffer result = new StringBuffer();
if (a.length lt 0) {
result.append(a[0]);
for (int i=1; i lt a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}