Java Dynamic Implementation Interface

Source: Internet
Author: User

 Package Com.yhouse.modules.daos;  Public Interface Iuserdao {    public  String getusername ();      Public String Say ();}

2.

 PackageCom.yhouse.modules.daos;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMethodproxyImplementsInvocationhandler {@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//if passing in is a concrete class that has been implemented (this demo skips this logic)        if(Object.class. Equals (Method.getdeclaringclass ())) {              Try {                  returnMethod.invoke ( This, args); } Catch(Throwable t) {t.printstacktrace (); }          //If it comes in an interface (CORE)}Else{System.out.println (Method.getname ()); returnrun (method, args); }          return NULL; }        /*** Core approach to interface implementation *@parammethod *@paramargs *@return     */     PublicObject Run (Method method,object[] args) {//TODO//such as remote HTTP calls//such as Remote Method Invocation (RMI)//....           return"Method call success!"; }  }

3.

 PackageCom.yhouse.modules.daos;ImportJava.lang.reflect.Proxy; Public classTest { Public Static voidMain (string[] args)throwsClassNotFoundException {//TODO auto-generated Method StubString ClassName= "Com.yhouse.modules.daos.IUserDao"; String MethodName= "Say"; Class CLZ=Class.forName (className); //Object newproxyinstance = proxy.newproxyinstance (IUserDao.class.getClassLoader (), New class[]{iuserdao.class},m );Methodproxy m=NewMethodproxy (); Object newproxyinstance= Proxy.newproxyinstance (Clz.getclassloader (),Newclass[]{clz},m); Iuserdao UD=((Iuserdao) newproxyinstance); String s=Ud.getusername ();               System.out.println (s); String S1=ud.         Say ();    System.out.println (S1); }}

Java Dynamic Implementation interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.