代码,供参考。 import java.lang.reflect.*;class BB {} class AA { private String[] str = {"1", "2", "3"}; private BB[] b; } public class Test { public Test() { } public static void main(String[] args) throws Exception{
AA o = new AA(); Class a = o.getClass(); Field[] fields = a.getDeclaredFields(); for(int i = 0; i < fields.length; i++){ Field f = fields[i]; f.setAccessible(true); String type = f.getType().toString(); System.out.println(f.getName()); System.out.println(type);
import java.lang.reflect.*;class BB
{}
class AA
{
private String[] str = {"1", "2", "3"};
private BB[] b;
}
public class Test {
public Test() {
}
public static void main(String[] args) throws Exception{
AA o = new AA();
Class a = o.getClass();
Field[] fields = a.getDeclaredFields();
for(int i = 0; i < fields.length; i++){
Field f = fields[i];
f.setAccessible(true);
String type = f.getType().toString();
System.out.println(f.getName());
System.out.println(type);
if(type.indexOf("[L") != 0){//判断是否为数组类型
Object object = f.get(o);
if (object == null) {
System.out.println("null");
} else {
Object[] array = (Object[]) object;
System.out.println(array.length);
}
}
}
}
}
String[] arr = new String[]{"a", "b", "c"};
if (arr.getClass().getComponentType() != null) {//判断是否为数组类型
System.out.println(java.lang.reflect.Array.getLength(arr));
}
}
package org.leelin.demo;import java.lang.reflect.Field;
import java.util.ArrayList;public class ReflectionTester { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] i=new Integer[]{1,2,3,4};
Object obj=new ArrayList();
getClassInfo(i);
getClassInfo(obj);
} private static void getClassInfo(Object o) {
// TODO Auto-generated method stub
Class c=o.getClass();
if(c.getName().indexOf('[')!=-1){
Object[] obj= (Object[]) o;
System.out.println(obj.length);
return;
}
Field[] fields=c.getDeclaredFields();
System.out.println("class:"+c.getName());
for(Field f:fields){
System.out.println(f.getName());
}
}
}