java動態代理--代理接口無實現類


轉載:https://blog.csdn.net/weixin_45674354/article/details/103246715

1.接口定義:

package cn.proxy;
 
public interface IHello {
    String say(String aa);
}

 

2.代理實現

package cn.proxy;
 
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
/**
 *  JDK動態代理代理類 
 *
 */
@SuppressWarnings("unchecked")
public class FacadeProxy implements InvocationHandler {  
    @Override  
    public Object invoke(Object proxy, Method method, Object[] args)  
            throws Throwable {  
        System.out.println("接口方法調用開始");  
        //執行方法  
        System.out.println("method toGenericString:"+method.toGenericString());
        System.out.println("method name:"+method.getName());
        System.out.println("method args:"+(String)args[0]);
        System.out.println("接口方法調用結束");  
        return "調用返回值";  
    }  
    
    public static <T> T newMapperProxy(Class<T> mapperInterface) {
        ClassLoader classLoader = mapperInterface.getClassLoader();
        Class<?>[] interfaces = new Class[]{mapperInterface};
        FacadeProxy proxy = new FacadeProxy();
        return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
      }

3.運行

package cn.proxy;
 
public class Test {
    public static void main(String[] args) {
        IHello hello = FacadeProxy.newMapperProxy(IHello.class);
        System.out.println(hello.say("hello world"));
    }
}

 

4.運行結果

接口方法調用開始
method toGenericString:public abstract java.lang.String cn.proxy.IHello.say(java.lang.String)
method name:say
method args:hello world
接口方法調用結束
調用返回值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM