JAVA代理实验1

本文介绍如何使用Java反射包中的Proxy类实现动态代理。通过创建一个简单的示例,展示了如何为接口生成代理对象,并通过InvocationHandler接口指定代理行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代理的主要类: java.lang.relfect.Proxy

最常用的方法就是生成代理对象:

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interface,
                                                 InvocationHandler h) throws IllegalArgumentException

例子:

/*
*InterfacePrint.java
*/


package org.proxy.test;

public interface InterfacePrint {
  
public void Hello(String str);
  
public void Byebye();
}

 使用Proxy示例:

/*
*proxyTest.java
*/


package org.proxy.test;

import java.lang.reflect.InvocationHandler;
import java.lnag.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public proxyTest implements InterfacePrint {
  
public proxyTes() {}

  
public void Hello(String str) {
    System.out.println(
"Hello World, " + str);
  }


  
public void Byebye() {
    System.out.println(
"Bye-bye...");
  }


  
public static void main(String[] args) throws Exception {
    proxyTest proxy 
= new proxyTest();
    InterfacePrint ip 
= (InterfacePrint)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                             proxy.getClass().getInterfaces(), 
new ProxyTestHandler<InterfacePrint>(proxyTest));
    System.out.println(
"IP.name = " + ip.getClass().getName());
    ip.Hello(
"天亮啦");
    ip.Byebye();
  }


  
static class ProxyTestHandler<T> implements InvocationHandler {
    
private T t;
    
    
public ProxyTestHandler(T t) {
      
this.t = t;
    }


    
public Object invoke(Object proxy, Mehtod method, Object[] args) throws Throwable {
      System.out.println(
"即将被调用的方法是" + method.getName());
      
return method.invoke(t, args);
    }

  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值