Cast a final class to a compatible interface that the class does not claim to implement

Viewed 799

Sometimes in Java, there is a case where you use a library that supplies a final class Car and you wish it implemented some Vehicle interface so that you could make Truck and Bus classes and treat them all as Vehicles in your code. But Car is final and it doesn't implement any interfaces.

How do I cast someone else's final Car class to my Vehicle interface so that I can pass it around like my other Vehicles? Every instance method on Vehicle would be 100% compatible with a similar method on Car in terms of instance method names, argument types, and return types. It would be equivalent from a Duck-Typing perspective.

I know I could make a MyCar extends Vehicle wrapper class that just delegates each method call to an internal Car object. That would be The Java Way. But I'm just wondering if there is a technique to actually cast one class to an unrelated (but 100% compatible) interface. It's OK if the answer is evil.

4 Answers
Related