Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package edu.mmc.proxy;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- interface Human{
- String getBrief();
- void eat(String food);
- }
- class SuperMan implements Human{
- @Override
- public String getBrief() {
- return "I can fly";
- }
- @Override
- public void eat(String food) {
- System.out.println("I like eat "+food);
- }
- }
- class ProxyFactory{
- public static Object getProxyInstance(Object obj){
- MyInvocationHandler handler = new MyInvocationHandler();
- handler.bind(obj);
- return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
- }
- }
- class MyInvocationHandler implements InvocationHandler{
- private Object obj;
- public void bind(Object obj){
- this.obj = obj;
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- return method.invoke(obj,args);
- }
- }
- public class ProxyTest {
- public static void main(String[] args) {
- SuperMan superMan = new SuperMan();
- Human proxy = (Human)ProxyFactory.getProxyInstance(superMan);
- proxy.eat("rice");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement