java我们如何知道字段是否是内部类的数组?
我阅读了本教程: 但仍然无法区分基元、数组和类(在反射中) 例如: 我有以下课程:java我们如何知道字段是否是内部类的数组?,java,reflection,Java,Reflection,我阅读了本教程: 但仍然无法区分基元、数组和类(在反射中) 例如: 我有以下课程: class MainClass { public MainClass() { memberSubClass = new SubClass(); arrayMemberSubClass = new SubClass[3]; for (int i = 0; i < 3; i++) { arrayMemberSubClass[i]
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;
}
输出为:
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
我做错了什么?来自您引用的页面:
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());
我认为这篇文章缺少的一点是如何使用反射获取数组元素的类型。这可以使用getComponentType()方法完成:
布尔值[]b=新的布尔值[5];
将元素的类型初始化为b.getClass().getComponentType();
System.out.println(元素的类型.getName());
mmm这确实很有帮助。因为数组可以是(整数、布尔、短…或其他内部定义的类)。。那么我需要检查所有类型吗?如果(field.getType().isArray()){Class thetypeofelements=field.getClass().getComponentType();返回null…:(
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());