Before I start, I know there are a bunch of answers to this question that suggest alternate approaches. I\'m looking for assistance to this particular approach as to whethe
The instanceof operator is a simple approach, when you don't own the classes. An instanceof expression is true when the object is the given class or a subclass.
You mention that you don't own the classes. The owner could introduce subclasses in a subsequent release. Say the owner introduces APlus as a subclass of A. An instance of APlus is an A. Code that works on an A should also work on an APlus. If you use instanceof, your code would continue to work -- without effort from you. If you use class names, it would fail -- without notice from your compiler.
If you're repeatedly switching on the same object, you might find it useful to wrap the object once in a wrapper class that implements an interface. Thereafter, you can simply call methods on the interface -- with no if, switch, or map.
public interface IWrapper {
public void handle();
public String describe();
}
public AWrapper implements IWrapper { ... }
public BWrapper implements IWrapper { ... }
public CWrapper implements IWrapper { ... }
public UnknownWrapper implements IWrapper { ... }
IWrapper wrap( Object o ) {
if ( o instanceof A ) return new AWrapper((A) o);
else if ( o instanceof B ) return new BWrapper((B) o);
else if ( o instanceof C ) return new CWrapper((C) o);
else return new UnknownWrapper(o);
}
Even in the guaranteed absence of subclasses, avoid specifying class names as literal strings in switch cases. This allows errors that the compiler will not find, which may cost you debugging time.