Using Java dynamic proxy

4.10 Summary

 

Proxy is also the only way to dynamically create classes from inside the Java programming language.

All of the implementation classes are created at runtime, leaving only the specification to be maintained by the developers. This specification also allows the creation of proxy classes for interfaces that were not available when the application was compiled. This means that Proxy can work with dynamic loading to enhance application flexibility.

 

4.9 Pitfalls of using Proxy

 

When this invoke method forwards the call p.equals(p) where p contains a reference to a proxy instance with a target of type PointImpl1, the return has the value false. This happens because the argument is a proxy instance, which is not of type PointImpl1.

 

public interface Point {
float getX();
float getY();
}
public class PointImpl1 implements Point {
private float x, y;
public PointImpl1( float x, float y ) { this.x = x; this.y = y; }

public float getX() { return x; }
public float getY() { return y; }
public boolean equals( Object obj ) {
if ( obj instanceof PointImpl1) {
PointImpl1 p = (PointImpl1)obj;
return p.x == x && p.y == y;
}
else
return false;
}
}
Now, consider another Point implementation shown in listing 4.19. Using this
implementation, p.equals(p) returns the expected value, true. The difference
between the two implementations is that while the first accesses values through
the concrete implementation, the second accesses these same values but through
the interface. The second succeeds because the proxy instance understands how
to respond to the interface.
public class PointImpl2 implements Point {
private float x, y;
public PointImpl2( float x, float y ) { this.x = x; this.y = y; }
public float getX() { return x; }
public float getY() { return y; }
public boolean equals( Object obj ) {
if ( obj instanceof Point) {
Point p = (Point)obj;
return p.getX() == x && p.getY() == y;
}
else
return false;
}
}
The general rule is if a class is expected to be proxied, a method parameter that
has that class as its type should be accessed through the interface. This can be
problematic if the interface does not provide the necessary access (as would be
the case if Point interface did not have both accessors).
Listing 4.19 PointImpl2 class

类一旦被代理,执行时的Object实例就已经不再是被代理的类,而是代理类

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值