遇到一个类,写了set方法,没有写get方法,于是其子类无法调用父类的一些属性。。。由于不能更改其代码,于是用反射机制很坑爹的获取了某个属性的值。。。调试时,自己编写了几个类用来测试,整理如下。
父类:
package date0415.pm.反射;
public class TestParent{
private String str1="www";//初始值。
private String str2="hao123";//初始值。
private int int1;
public TestParent() {
super();
}
public TestParent(String str1, String str2,int int1) {
super();
this.str1 = str1;
this.str2 = str2;
this.int1 = int1;
}
/**
* 打印方法,负责打印该类变量的值
*/
public void print(){
System.out.println(str1);
System.out.println(str2);
System.out.println(int1);
}
}
子类:
package date0415.pm.反射;
import java.lang.reflect.Field;
public class TestChild extends TestParent{
public TestChild() {
super();
}
public TestChild(String str1, String str2, int mVerticalSpacing) {
super(str1, str2, mVerticalSpacing);
}
/**
* 获取指定字段的值(是一个对象)
*/
public Object getSpecificedFieldObject(String fieldName) {
Class<?> clazz = this.getClass().getSuperclass();
Object object = null;
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
object = field.get(this);
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
return object;
}
}
主方法类:
package date0415.pm.反射;
public class TestMain{
public static void main(String[] args){
// TestParent t=new TestParent();
// t.print();
//
// Field[] f = t.getClass().getDeclaredFields();
//
// for(int i=0;i<f.length;i++){
// f[i].setAccessible(true);
// if (f[i].getName() == "str2") {
// f[i].set(t, "japan");
// };
// }
// t.print();
test1();
System.out.println("\n\n---------分割线--------\n\n");
test2();
}
/**
* 测试方法1
*/
private static void test1(){
TestChild child = new TestChild();
String v1 = (String) child.getSpecificedFieldObject("str1");
String v2 = (String) child.getSpecificedFieldObject("str2");
int v3 = (int) child.getSpecificedFieldObject("int1");
System.out.println("反射取值:");
System.out.println("str1 = "+v1);
System.out.println("str2 = "+v2);
System.out.println("str3 = "+v3);
System.out.println("\n调用继承自父类的方法打印:");
child.print();//调用父类方法打印值
}
/**
* 测试方法2
*/
private static void test2(){
TestChild child = new TestChild("你好", "世界", 10086);
String v1 = (String) child.getSpecificedFieldObject("str1");
String v2 = (String) child.getSpecificedFieldObject("str2");
int v3 = (int) child.getSpecificedFieldObject("int1");
System.out.println("反射取值:");
System.out.println("str1 = "+v1);
System.out.println("str2 = "+v2);
System.out.println("str3 = "+v3);
System.out.println("\n调用继承自父类的方法打印:");
child.print();//调用父类方法打印值
}
}
打印结果如下:
反射取值:
str1 = www
str2 = hao123
str3 = 0
调用父类方法打印:
www
hao123
0
---------分割线--------
反射取值:
str1 = 你好
str2 = 世界
str3 = 10086
调用父类方法打印:
你好
世界
10086