口袋妖怪黑白自由岛:关于java反射的问题,高手请进

来源:百度文库 编辑:高校问答 时间:2024/05/03 03:01:03
现在有一个类
public class SOMECLASS {
public static final String strSomething[];
static {

strSomething=new String[4];
strSomething[0]="haha";
strSomething[1]="haha1";
strSomething[2]="haha2";
strSomething[3]="haha3";
}

}

现在我想利用类似如下代码:
Class c=Class.forName("SOMECLASS");
Field f=c.getField("strSomething");
........... //不会编了

获得strSomething的length以及每个元素的值,怎么弄?谢谢谢谢

也就是反射数组,

java.lang.Class 类中有一个方法测试数组 isArray()
和 取出数组Class类型的方法 getComponentType()

java.lang.reflect.* 包 专门提供了一个可以反射数组的类 Array
Array.getLength(Object ); 得到长度
Array.getXXX(Object,int); 得到指定的值
Array.setXXX(Object,int); 设置指定的值
(XXX 表示类型 int,Boolean,float... 默认返回Object)

代码:

public class SOMECLASS {
public static final String strSomething[];
static {

strSomething=new String[4];
strSomething[0]="haha";
strSomething[1]="haha1";
strSomething[2]="haha2";
strSomething[3]="haha3";

}
}

反射类:

Class c = null;
Field f = null;
try {
c = Class.forName("SOMECLASS");
f = c.getDeclaredField("strSomething");

} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}

Class fc = f.getType(); //字段的反射类

System.out.println("反射类的类型: "+c.getName());

if(fc.isArray()){
System.out.println("反射字段的类型: " + fc.getName());

int len = Array.getLength(SOMECLASS.strSomething);
System.out.println("数组长度: " + len);

for(int i = 0; i<len; i++){
System.out.println("第"+i+"个元素: "+String.valueOf(Array.get(SOMECLASS.strSomething,i)));
}
}

Class c=Class.forName("SOMECLASS");
Field f=c.getField("strSomething");

////////获得field的值,并显示
String[] s=(String[])f.get(null);
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}

祝你好运!

回答的不错!顶一下.