利用反射访问私有属性、调用私有方法
2014-02-28 09:45
676 查看
访问私有属性的代码:
package com.tyxh.create;
public class Customer {
private int a = 1;
public int getA() {
return a;
}
}
package com.tyxh.create;
import java.lang.reflect.Field;
public class Private {
public static void main(String[] args) throws Exception {
//实例化
Customer customer = (Customer) Class.forName("com.tyxh.create.Customer").newInstance();
System. out.println( "修改之前 : " + customer.getA());
Class<? extends Customer> c = customer.getClass();
Field field = c.getDeclaredField( "a");
field.setAccessible( true);
field.set(customer, 2);
System. out.println( "修改之后: " + customer.getA());
}
}
调用私有方法的代码:
package com.tyxh.create;
public class Customer {
private int a = 1;
public int getA() {
return a;
}
}
package com.tyxh.create;
import java.lang.reflect.Field;
public class Private {
public static void main(String[] args) throws Exception {
//实例化
Customer customer = (Customer) Class.forName("com.tyxh.create.Customer").newInstance();
System. out.println( "修改之前 : " + customer.getA());
Class<? extends Customer> c = customer.getClass();
Field field = c.getDeclaredField( "a");
field.setAccessible( true);
field.set(customer, 2);
System. out.println( "修改之后: " + customer.getA());
}
}
调用私有方法的代码:
package com.tyxh.create; public class Customer { private String b1(String n) { return "你好啊," + n + " ,你都访问我私有方法啦。。。NB 啊" ; } private void b2() { System. out.println( "我擦,都访问我私有方法了啊。。。碉堡了" ); } } package com.tyxh.create; import java.lang.reflect.Method; public class Private { public static void main(String[] args) throws Exception { Customer customer = (Customer) Class.forName("com.tyxh.create.Customer").newInstance(); Class<? extends Customer> c = customer.getClass(); Method m1 = c.getDeclaredMethod( "b1", new Class[]{String.class}); m1.setAccessible( true); String str = (String) m1.invoke(customer, new Object[]{"tyxh"}); System. out. println(str); Method m2 = c.getDeclaredMethod("b2", null) ; m2.setAccessible( true); m2.invoke(customer, null); } }
相关文章推荐
- 利用反射调用私有方法、访问私有属性
- 利用反射对私有属性/方法进行设置/调用(转自己贴)
- Java记录 -88- 利用反射机制调用对象的私有方法和属性
- Java记录 -88- 利用反射机制调用对象的私有方法和属性
- java利用反射访问类的私有(private)属性及方法
- 利用反射对私有属性/方法进行设置/调用
- java利用反射访问类的私有(private)属性及方法
- 利用java的反射机制调用类的私有方法及私有属性
- java利用反射来调用一个类的私有方法
- 如何利用反射去访问一个私有的方法
- Java通过反射调用其他类的私有属性和私有方法
- Java反射之访问私有属性或方法
- Java反射高级应用--利用反射调用类的私有方法修改私有方法值,以及替换Java的类成员数据
- Java反射学习总结二(用反射调用对象的私有属性和方法)
- java反射访问私有属性和方法
- Java反射之访问私有属性或方法
- Java反射高级应用--利用反射调用类的私有方法修改私有方法值,以及替换Java的类成员数据
- java 反射方式访问私有属性和方法
- java反射应用--调用方法与访问属性
- 利用反射调用类及其属性和方法