Reputation: 291
I m facing problem while retriving fields types in class.
class Test {
public int x;
public int[] y;
public String[] names;
}
public class Main {
static void main(String[] args) {
try {
printAttributes(Class.forName("Test"));
}
catch(Exception ex){}
}
static void printAttributes(Class clazz) {
Field[] fields=clazz.getFields();
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i].getType().getName().toString()+" "+ fields[i].getName().toString());
}
}
}
Output
int x //its OK
[I y //I need **int[] y**
[Ljava.lang.String; names //I need **java.lang.String[] names**
How can I get the attribute types in correct format?
Upvotes: 0
Views: 9079
Reputation: 11257
The obscure phrase
[Ljava.lang.String
is the reified type of the array, where[L
indicates that it is an array of reference type andjava.lang.String
is the component type of the array.
Excerpt from the book Java Generics and Collections by Maurice Naftalin, Philip Wadler, published by O'Reilly
Upvotes: 0
Reputation: 597076
You can't. Arrays' toString()
method uses the [X
convention. You can create you own utility that will do what you want. Like
public class ArrayUtils {
public static String toClassName(Class<?> clazz) {
if (clazz.isArray()) {
return clazz.getComponentType().getName() + "[]";
} else {
return clazz.getName();
}
}
}
Update: Péter Török added this as answer but then deleted it. In fact you can use getCanonicalName()
rather than getName()
. That method does roughly what the about utility method does,i.e it will give you what you want. But you can still have your utility class if you want finer control on the representation (for example want to omit the FQN at some point, etc).
Upvotes: 2