2014-11-22 68 views
0

我阅读这个教程: http://jroller.com/eyallupu/entry/two_side_notes_about_arraysjava如何知道field是内部类的数组?

但仍然无法弄清楚如何原始,数组和类(在反射)

例如区分: 我有下面的类:

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 

我希望得到follwing输出:

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

从页面引用您:

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()); 
+0

MMM它确实帮助不大。因为数组可以是(Integer,Boolean,Short ...或其他内部定义的类)..所以我需要检查所有类型? – user3668129 2014-11-22 16:38:57

+0

if(field.getType()。isArray()){ 类 theTypeOfTheElements = field.getClass()。getComponentType(); 返回null ... :( – user3668129 2014-11-22 16:46:10

相关问题