Dynamic Proxies in Java

  

Overview

 

Usually, the proxy class is already available as Java bytecodes, having been compiled from the Java source file for the proxy class.When needed, the bytecodes for the proxy class are loaded into the Java Virtual Machine and proxy objects can then be instantiated.But, in some circumstances, it is useful to dynamically generate the bytecodes for the proxy class at runtime. This module will look at the techniques for dynamically generating proxies in Java and the benefits of doing so.

Proxy objects are useful in many situations to act as an intermediary between a client object and a target object.

 

 

 

 

 

 

 

 

 

 

 

 Now let's have the client interact with the target object through a proxy.Remember that the main intent of a proxy is to control access to the target object, rather than to enhance the functionality of the target object.

Ways that proxies can provide access control include:

 

1. Synchronization

2. Authentication

3. Remote Access

4. Lazy instantiation

 

 

 Here's our VehicleProxy class:

 

/** * Class VehicleProxy. */ public class VehicleProxy implements IVehicle { private IVehicle v; public VehicleProxy(IVehicle v) {this.v = v;} public void start() { System.out.println("VehicleProxy: Begin of start()"); v.start(); System.out.println("VehicleProxy: End of start()"); } // stop(), forward(), reverse() implemented similarly. // getName() not shown. }

 
  

 

 

 

 

  /** * Class Client2. * Interacts with a Car Vehicle through a VehicleProxy. */ public class Client2 { public static void main(String[] args) { IVehicle c = new Car("Botar"); IVehicle v = new VehicleProxy(c); v.start(); v.forward(); v.stop(); } }

 

 

 

 

 

 

 

 

 

 Output for the vehicle example with a proxy:

 

    VehicleProxy: Begin of start()

   Car Botar started

   VehicleProxy: End of start()

   VehicleProxy: Begin of forward()

   Car Botar going forward

   VehicleProxy: End of forward()

   VehicleProxy: Begin of stop()

   Car Botar stopped

   VehicleProxy: End of stop()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值