Home  >  Article  >  Java  >  Use of java dynamic proxy

Use of java dynamic proxy

巴扎黑
巴扎黑Original
2016-12-02 09:58:571463browse

1. Interface Human.java

public interface Human {  
    void say();  
}

2. Human implementation class Person

public class Person implements Human {  
  
    @Override  
    public void say() {  
        System.out.println("haha");  
    }  
  
}


3. Processing class

import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
  
public class Hander implements InvocationHandler {  
    private Object obj;  
    public Hander(Object obj) {  
        this.obj = obj;  
    }  
    public Hander() {  
    }  
    @Override  
    public Object invoke(Object proxy, Method method, Object[] args)  
            throws Throwable {  
        System.out.println("before");  
        method.invoke(obj, args);  
        System.out.println("after");  
        return null;  
    }  
  
}


4. Use

import java.lang.reflect.Proxy;  
  
public class Main {  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        Human i = (Human) Proxy.newProxyInstance(Thread.currentThread()  
                .getContextClassLoader(), Person.class.getInterfaces(),  
                new Hander(new Person()));  
        i.say();  
    }  
  
}


5. Output results

before  
haha  
after


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:trim() function in JavaNext article:trim() function in Java