Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting of interfaces

Tags:

java

c#

interface

interfaces provide a useful abstraction capability. One can have a class Foo implement some interfaces, say A, B, and C. Some client code may get a reference of type A, others one of type B, etc. each actually the same Foo object but the interface exposing only a narrow subset of the functionality. Of course, evil client code can try to cast the A reference to Foo, then access the other functionality.How to prevent this?

like image 287
Srinivas Reddy Thatiparthy Avatar asked Apr 12 '10 10:04

Srinivas Reddy Thatiparthy


2 Answers

This is called a "malicious cast" and you can prevent it by having a wrapper that implements only the narrow interface you want to expose (by delegating to a private reference to the object that you would have otherwise directly passed to the evil client).

However, if the client is not only evil, but powerful as well, he might be able to use reflection to get to the hidden reference anyway.

like image 95
Thilo Avatar answered Oct 15 '22 06:10

Thilo


Normal inheritance will always allow it, you can do nothing with it. If you want to expose some class as interface but hide other methods use Adapter pattern (google it)

like image 33
Andrey Avatar answered Oct 15 '22 06:10

Andrey