java 反射 成员变量_java基础--反射(成员变量)
這里介紹通過反射獲取對象的成員變量,以及修改成員變量。
package Reflect.field;
public class Point {
int y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(int y) {
super();
this.y = y;
}
}
package Reflect.field;
public class ReflectPoint extends Point {
protected int x; // 必須要用public修飾 否則反射取不到
public int y; // 必須要用public修飾 否則反射取不到
public String str1 = "hello";
public String str2 = "world";
public String str3 = "OK";
public ReflectPoint(int x, int y) {
super(10);
this.x = x;
this.y = y;
}
// 覆蓋了此方法,就可以直接System.out.println(new ReflectPoint());
@Override
public String toString() {
return str1 + ":" + str2 + ":" + str3;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
package Reflect.field;
import java.lang.reflect.Field;
/**
* 成員變量的反射
*
* @author xiaoyu
*
*/
public class Test {
public static void main(String[] args) throws Exception {
// 測試通過反射 獲取對象的變量
ReflectPoint pt1 = new ReflectPoint(3, 5);
Point pt = new Point(99);
Field fieldY = pt1.getClass().getField("y"); // 這樣只能取得public 修飾的y
Field allFieldY = pt.getClass().getDeclaredField("y"); // 這樣所有的y,不管是什么修飾符
// fieldY不是對象上的變量,它是類上的。 fieldY.get(pt1)
System.out.println(fieldY.get(pt1)); // 5
System.out.println(allFieldY.get(pt)); // 99
Field fieldX = pt1.getClass().getDeclaredField("x");
// 暴力反射 ,不管x 是不是Public
// 修飾的,都可以取到(用了getDeclaredField("x"),setAccessible(true)可以不用寫了)
// fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1)); // 3
// 下面測試通過反射改變一個對象的變量的值
changeStringValue(pt1);
// 打印出pt1中的String類型的值
System.out.println(pt1);
}
/**
* 該方法可以改變對象obj中String類型的變量
*
* @param obj
*/
public static void changeStringValue(Object obj) throws Exception {
Field[] fileds = obj.getClass().getFields(); // 獲取obj對象的所以變量
for (Field field : fileds) { // 循環找出是String類型的變量
// 字節碼只有一份,所以可以==,而且比equals()方法更好
if (field.getType() == String.class) {// 如果是String類型的,則改變其值
String oldValue = (String) field.get(obj);
String newValue = oldValue.replace('o', 'h');
field.set(obj, newValue);// 當然你也可以設置成新的值 ;field.set(obj, "WWW");
}
}
}
}
總結
以上是生活随笔為你收集整理的java 反射 成员变量_java基础--反射(成员变量)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode-551-Student
- 下一篇: css标签选择器、类名选择器、多类名选择