我读了这个教程: http://jroller.com/eyallupu/entry/two_side_notes_about_arrays
但仍然无法弄清楚如何区分基元,数组和类(反射)
例如: 我有以下课程:
class MainClass {
public MainClass() {
memberSubClass = new SubClass();
arrayMemberSubClass = new SubClass[3];
for (int i = 0; i < 3; i++) {
arrayMemberSubClass[i] = new SubClass();
}
array_int_member = new int[5];
}
class SubClass {
public int x;
public short y;
}
public SubClass memberSubClass;
public SubClass[] arrayMemberSubClass;
public int int_member;
public int[] array_int_member;
}
我有以下方法(在其他课程中):
public void doSometing(Object obj) {
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
if (field.getType().isArray()) {
if (field.getType().isPrimitive()) {
logger.debug(field.getName() + " is array of primitives");
} else {
logger.debug(field.getName() + " is array of classes");
}
}
else {
if (field.getType().isPrimitive()) {
logger.debug(field.getName() + " is primitives");
} else {
logger.debug(field.getName() + " is class");
}
}
}
}
输出结果为:
0 [main] DEBUG Logic - memberSubClass is class
1 [main] DEBUG Logic - arrayMemberSubClass is array of classes
1 [main] DEBUG Logic - int_member is primitives
1 [main] DEBUG Logic - array_int_member is array of classes
我希望得到以下结果:
0 [main] DEBUG Logic - memberSubClass is class
1 [main] DEBUG Logic - arrayMemberSubClass is array of classes
1 [main] DEBUG Logic - int_member is primitives
1 [main] DEBUG Logic - array_int_member is array of primitives
我做错了什么?
答案 0 :(得分:0)
从您引用的页面:
One thing I think was missing in the post is how to get the type of the array elements using reflection. This can be done using the getComponentType() method:
Boolean[] b = new Boolean[5];
Class<?> theTypeOfTheElements = b.getClass().getComponentType();
System.out.println(theTypeOfTheElements.getName());