I am working on a tool that writes java files. At a given point I have to write an array declaration. I have implemented the following methods:
public static String arrayToCode(Long[] arr, String arrName) {
StringBuilder sb = new StringBuilder();
sb.append("Long[]" + arrName + " = { ");
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i] + "L, ");
}
sb.append("};");
return sb.toString();
}
public static String arrayToCode(String[] arr, String arrName) {
StringBuilder sb = new StringBuilder();
sb.append("String[]" + arrName + " = { ");
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i] + "L, ");
}
sb.append("};");
return sb.toString();
}
public static String arrayToCode(Double[] arr, String arrName) {
StringBuilder sb = new StringBuilder();
sb.append("Double[]" + arrName + " = { ");
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i] + "L, ");
}
sb.append("};");
return sb.toString();
}
However, I would like to make a single and generic method for all sorts of arrays, the thing is that I don’t know how to handle the type with generics, i.e. how would I know it is a Long, String or Double array?
You can accept an
Object[]and then usegetClass()to figure out what type it really is.An alternative implementation of
getArrayType()might beIf you’re really trying to generate code you probably should just use the fully qualified name, in which case you can replace
getSimpleName()above withgetName()(which will returnjava.lang.Long, e.g.)