···
//动态代理的举例
interface human{
String getBelief();
void eat();
}
class humanUtil{
public void method1(){
System.out.println("=============== 前置方法==============");
}
public void method2(){
System.out.println("===============后置方法==============");
}
}
//被代理类
class SuperMan implements human{
@Override
public String getBelief() {
return "i can fly";
}
@Override
public void eat() {
System.out.println("eating food...");
}
}
//实现动态代理,需要解决的问题
//1.如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象
//2.当通过代理类的对象调用方法时,如何动态的调用被代理类的同名方法
class ProxyFactory {
//调用此方法,返回一个代理类对象。解决问题一
public static Object getProxyInstance(Object object){
MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
myInvocationHandler.bind(object);
return java.lang.reflect.Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),myInvocationHandler);
}
}
class MyInvocationHandler implements InvocationHandler{
private Object obj;
public void bind(Object obj){
this.obj = obj;
}
//当我们通过代理类的对象,调用方法a时,就会自动调用如下方法: invoke()
//将被代理类要执行的方法a的功能声明在invoke中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
humanUtil humanUtil = new humanUtil();
//前置通知
humanUtil.method1();
//method: 即为代理类对象调用的方法,此方法也就作为被代理类对象要调用的方法
Object value = method.invoke(obj, args);
//上述方法的返回值就作为当前类中的invoke的返回值
//后置通知
humanUtil.method2();
return value;
}
}
public class Proxy {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
//proxyInstance: 被代理类的对象
human proxyInstance = (human)ProxyFactory.getProxyInstance(superMan);
//通过代理类调用对象时,会自动调用被代理中的同名方法
proxyInstance.eat();
System.out.println(proxyInstance.getBelief());
NikeClothFactory factory = new NikeClothFactory();
ClothFactory proxyInstance1 = (ClothFactory)ProxyFactory.getProxyInstance(factory);
proxyInstance1.produceCloth();
}
}
···
public class getStructure {
//属性
@Test
public void testField() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
Class<person> personClass = person.class;
person person = personClass.newInstance();
//获取指定的属性
Field name = personClass.getDeclaredField("name");
name.setAccessible(true);
//设置指定的属性
name.set(person,"asdf");
}
//方法
@Test
public void testMethod() throws Exception {
Class<person> personClass = person.class;
person person = personClass.newInstance();
Method show = personClass.getDeclaredMethod("show");
show.setAccessible(true);
Object invoke = show.invoke(person,null);
System.out.println(invoke);
//调用静态方法
Method staticmethod = personClass.getDeclaredMethod("staticmethod");
staticmethod.setAccessible(true);
Object invoke1 = staticmethod.invoke(person.class,null);
System.out.println(invoke1);
//调用指定构造器
Constructor<Reflection.person> declaredConstructor = personClass.getDeclaredConstructor(String.class, int.class);
Reflection.person asdf = declaredConstructor.newInstance("asdf", 123);
System.out.println(asdf);
}
}