Reputation: 262514
If you implement an interface in Java, there is nothing to prevent the caller from looking at what concrete implementation you have supplied, casting to that class and calling methods that are not in the interface. I believe this is called "malicious downcasting".
A way to prevent this is to create a wrapper that only has the interface's methods and does not expose the implementation instance to which it delegates. Short of reflection to private variables you should be safe.
Is there a way to automatically create these kind of wrappers (at run-time, not using a code creation wizard in the IDE, because that still creates a source file that needs to be maintained) ?
Upvotes: 2
Views: 282
Reputation: 223023
I like James Black's answer, but for diversity, I'll post an alternative approach.
You can use java.lang.reflect.Proxy
to do this. See this post for some code I wrote (for a different question) that uses Proxy
; you can use similar code, if you strip out the synchronization stuff.
Upvotes: 7
Reputation: 41858
Another way to protect against this is to use a factory class, and have the implementation be a private inner class of the factory. Only the factory can see it and it will return only the interface type so there is no concrete implementation to cast against.
Upvotes: 8