public interface subject {
//業務操作
public void dosomething(string abc);
}
-----
public class realsubject implements subject {
public void dosomething(string str) {
system.out.println("do something!---->" + str);
----
public class myinvocationhandler implements invocationhandler {
//被代理的對象
private object target = null;
//通過構造函數傳遞一個對象
public myinvocationhandler(object _obj){
this.target = _obj;
//代理方法
public object invoke(object proxy, method method, object[] args)
throws throwable {
//設定傳回值
object result = null;
//前置通知
this.before();
//執行被代理的方法
result = method.invoke(this.target, args);
//後置通知
this.after();
//傳回值
return result;
public void before(){
system.out.println("執行before方法");
public void after(){
system.out.println("執行after方法");
public class dynamicproxy {
//定義要代理哪個類
private object obj =null;
//通過構造函數傳遞被代理對象
public dynamicproxy(object _obj){
class c = _obj.getclass();
//生成被代理類的代理類
this.obj = proxy.newproxyinstance(c.getclassloader(), c.getinterfaces(), new myinvocationhandler(_obj));
//執行代理類的方法
public object exec(string methodname,object...args){
//方法中的參數類型
class[] c= new class[args.length];
int i=0;
//獲得參數的類型
for(object o:args){
c[i] = o.getclass();
i++;
try {
//根據方法名稱和參數類型查找到唯一一個方法
method method=this.obj.getclass().getmethod(methodname, c);
//執行該方法
result = method.invoke(this.obj, args);
} catch (exception e) {
e.printstacktrace();
public class client {
public static void main(string[] args) {
dynamicproxy proxy = new dynamicproxy(new realsubject());
string[] str = {"1111"};
proxy.exec("dosomething",str);