I assume that you really profiled your code and found that your use of instanceof is a non-trivial performance hit? If not, you will almost certainly solve a problem that is not worth your time to resolve.
If all you do is code:
if ( something instanceof MyClass ) { MyClass mySomething = (MyClass) something; //... } else { //exceptional case }
Then first you can try throwing and letting ClassCastException be your "exceptional case":
try { MyClass mySomething = (MyClass) something; } catch (ClassCastException cce) {
Now, although it may be premature optimization, it would be premature to rethink your design. The danger of using instanceof is a designer smell. In general, you should use generics and polymorphism in ways that reduce the number of times you would use instanceof (and indeed casting) to (almost) zero.
If, depending on the type of object, different code is to be executed, consider making this code a method of an instance of the object and have different types corresponding to the interface.
If you find that you βknowβ that the object is of a certain type, but you took some step that made the compiler lose this fact (for example, you put it in a raw List ), this may be a candidate for generation.
source share