www

导航

Java动态代理

Fruit.java

package com.wzh.proxy.fruit;

public interface Fruit {
    public void eat();
}

Apple.java

package com.wzh.proxy.fruit.impl;

import com.wzh.proxy.fruit.Fruit;

public class Apple implements Fruit{

    @Override
    public void eat() {
        
        System.out.println("eating apple");
        
    }

}

ProxyHandler.java

package com.wzh.proxy.fruit.proxyhandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.wzh.proxy.fruit.Fruit;

public class ProxyHandler implements InvocationHandler{
    
    private Fruit fruit;
    
    public ProxyHandler(Fruit _fruit) {
        fruit = _fruit;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        
        Object result = null;
        System.out.println("start");
        result = method.invoke(fruit, args);
        System.out.println("over");
        
        return result;
    }

}

Run.java

package com.wzh.proxy.run;

import java.lang.reflect.Proxy;

import com.wzh.proxy.fruit.Fruit;
import com.wzh.proxy.fruit.impl.Apple;
import com.wzh.proxy.fruit.impl.Orange;
import com.wzh.proxy.fruit.proxyhandler.ProxyHandler;

public class Run {

    public static void main(String[] args) {
        
        Orange orange = new Orange();
        ProxyHandler handler = new ProxyHandler(orange);
        Fruit fruitProxy = (Fruit) Proxy.newProxyInstance(orange.getClass().getClassLoader(), orange.getClass().getInterfaces(), handler);
        fruitProxy.eat();
    }
    
}

 

posted on 2018-09-05 14:46  www_practice  阅读(168)  评论(0编辑  收藏  举报