public ReflectTest() {// TODO Auto-generated constructor stub}//创建一个改变属性值的方法private static void changeStringValue(Object obj) throws IllegalArgumentException, IllegalAccessException{//建立一个Field的数组对象存放获取对象的多个属性Field[]
 fields=obj.getClass().getFields();for(Field field:fields){//遍历对象//推断是否存在属性类型为字符串的类型if(field.getType() == String.class){//获取属性为String的对象 String oldValueString=(String)field.get(obj);//将新的字符串替换老的字符串String newValueString=oldValueString.replace("a", "b");//对配置的对象设值新值field.set(obj,
 newValueString);}}}public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {// TODO Auto-generated method stub//System.out.println(pt1);//对ReflectPoint类的属性进行反射ReflectPoint
 pt1=new ReflectPoint(3,5);//得到一个字段Field fieldY=pt1.getClass().getField("y");//取出在某个对象属性上的值System.out.println(fieldY.get(pt1));//同理取出其它对象上的值Field fieldX=pt1.getClass().getDeclaredField("x");//取出私有的时候是看不到的会报错//对于被设置为私有的属性 我们进行强制(暴力)反射 就是对要获取的属性进行setAccessible()fieldX.setAccessible(true);System.out.println(fieldX.get(pt1));changeStringValue(pt1);System.out.println(pt1);String
 str1="abc";//用反射得到类中的某一个方法 用Method类来完毕 用str1对象身上的charAt(1) str1.charAt(1)Method methodChartAt=String.class.getMethod("charAt", int.class);System.out.println(methodChartAt.invoke(pt1.str2, 1));//这里是取出反射文件里的str2字符串的第二个单词System.out.println(str1.charAt(1));//当前对象中的第二个单词}}


该类为被反射的类

package com.tuozou.test;

public class ReflectPoint {

	private int x;
	public int y;
	public String str1="able";
	public String str2="apple";
	public String str3="great";
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	public ReflectPoint() {
		// TODO Auto-generated constructor stub
	}
	//为了能看到映射替换的效果 还有必要覆盖toString的方法
	@Override
	public String toString(){
		return str1+":"+str2+":"+str3;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}



相关文章:

  • 2022-02-16
  • 2022-02-20
  • 2022-12-23
  • 2021-12-10
  • 2022-03-02
  • 2022-12-23
  • 2021-08-01
  • 2021-05-24
猜你喜欢
  • 2022-12-23
  • 2021-08-04
  • 2021-07-27
  • 2021-11-15
  • 2021-09-05
  • 2022-12-23
  • 2022-01-12
相关资源
相似解决方案