java 暴力反射_java 反射和暴力反射 两个DEMO

 
 
该类为反射函数 获取和暴力获取ReflectPoin类中的属性
package com.tuozou.test;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;public class ReflectTest {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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值