RT, 我想要得到一个类中为数组类型变量的值,我在Field的API中找到一个get()方法,但是貌似得到的是这个数组的引用(一个象内存地址的字串),该怎么拿到里面的值呢?先谢谢各位了。
写了个例子,请仔细查看代码,具体过程需要你自己对照java API 再研究,
先定义了一个普通的学生类,如下:
public class Student {对学生类进行反射
public class Test3 {希望你采纳。 谢谢。
本回答被提问者采纳package com.cs.gang;
import java.lang.reflect.Field;
/**
* Created by IntelliJ IDEA.
* User: gang-liu
* Date: 2/26/14
* Time: 2:12 PM
*/
public class ReflectTest {
private String[] strData;
private int[] intData;
public ReflectTest() {
strData = new String[]{"one", "two", "three"};
intData = new int[]{1, 2, 4, 5, 6};
}
public ReflectTest(String[] strData, int[] intData) {
this.strData = strData;
this.intData = intData;
}
public String[] getStrData() {
return strData;
}
public void setStrData(String[] strData) {
this.strData = strData;
}
public int[] getIntData() {
return intData;
}
public void setIntData(int[] intData) {
this.intData = intData;
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
final ReflectTest test = new ReflectTest();
final Field strField = ReflectTest.class.getDeclaredField("strData");
strField.setAccessible(true);
final String[] data = (String[]) strField.get(test);
for(final String d : data){
System.out.println(d);
}
final Field intField = ReflectTest.class.getDeclaredField("intData");
intField.setAccessible(true);
final int[] intDatas = (int[]) intField.get(test);
for(final int intData : intDatas){
System.out.println(intData);
}
}
}