java 反射和暴力反射 两个DEMO

</pre><pre code_snippet_id="402084" snippet_file_name="blog_20140622_5_9350254" name="code" class="java">
</pre><pre code_snippet_id="402084" snippet_file_name="blog_20140622_4_2588858" name="code" class="java">
<pre code_snippet_id="402084" snippet_file_name="blog_20140622_4_2588858" name="code" class="java">该类为反射函数 获取和暴力获取ReflectPoin类中的属性
</pre><pre code_snippet_id="402084" snippet_file_name="blog_20140622_6_9143294" name="code" class="java">package com.tuozou.test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">public class ReflectTest {</span>
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

	}

}



原文地址:https://www.cnblogs.com/zhchoutai/p/6893881.html