`
tuicwy
  • 浏览: 8210 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

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实例就已经不再是被代理的类,而是代理类

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics