Package com.kaige123; /** * Programmer * @author Edith */publicinterfaceChengxuyuan{ / * * Write code Method */public voidXiedaima();}
Package com.kaige123; /** * Programmer Interface Implementation class * @author Edith */ Public classChengxuyuanimplimplementsChengxuyuan {public voidXiedaima(){ System.out.println ("Write code. .."); } }
Packagecom.kaige123;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;/** * Processing class * @author Edith */ Public class Cxyhandler implements Invocationhandler {//Programmer implements object passingPrivateChengxuyuan C;Public cxyhandler(Chengxuyuan c) { This. C = C; }/** * Programmer interface method as long as the call will be notified to eat the method * @param proxy Object * @param method tells you to call the methods encapsulated object *
@param args parameter *
/ public Object invoke(object Proxy, Method method, object[] args) throws Throwable{System.out.println ("Method Name:"+method.getname ()); System.out.println ("have a cup of coffee, put on your clothes first."); Object Obj=method.invoke (c, args);//Call methodSystem.out.println ("Take off your clothes and continue drinking coffee.");returnObj }}
Packagecom.kaige123;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;/** * Test class * @author Edith * */ Public class Test {Public static void main(string[] args) {//Implement class objectChengxuyuanimpl Chengxuyuanimpl =NewChengxuyuanimpl ();//Get reflective classClass classs = Chengxuyuanimpl.getclass ();//Create a processing class and pass the implementation class objectCxyhandler handler =NewCxyhandler (Chengxuyuanimpl);//Start creating proxy objects and convert proxy objects to interface typesChengxuyuan Chengxuyuan = (Chengxuyuan) proxy.newproxyinstance (classs.getclassload ER (), classs.getinterfaces (), handler);//Call method like >>>invoke (Object Proxy, method, object[] args) >> Xiedaima () >> call completeChengxuyuan.xiedaima (); }}
Results:
Method Name: Xiedaima drink a coffee, first put on the clothes to write code ... Take off your clothes and continue drinking coffee I
Java Reflection mechanism Dynamic Proxy