Home > Java > javaTutorial > body text

Use of java dynamic proxy

巴扎黑
Release: 2016-12-02 09:58:57
Original
1424 people have browsed it

1. Interface Human.java

public interface Human {  
    void say();  
}
Copy after login

2. Human implementation class Person

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


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;  
    }  
  
}
Copy after login


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();  
    }  
  
}
Copy after login


5. Output results

before  
haha  
after
Copy after login


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!