Is This Use of the “instanceof” Operator Considered Bad Design?

The Visitor pattern is typically used in such cases. Although the code is a bit more complicated, but after adding a new RecordType subclass you have to implement the logic everywhere, as it won’t compile otherwise. With instanceof all over the place it is very easy to miss one or two places. Example: public abstract … Read more

instanceof check in EL expression language

You could compare Class#getName() or, maybe better, Class#getSimpleName() to a String. <h:link rendered=”#{model[‘class’].simpleName eq ‘ClassA’}”> #{errorMessage1} </h:link> <h:link rendered=”#{model[‘class’].simpleName eq ‘ClassB’}”> #{errorMessage2} </h:link> Note the importance of specifying Object#getClass() with brace notation [‘class’] because class is a reserved Java literal which would otherwise throw an EL exception in EL 2.2+. The type safe alternative is … Read more

How to check if a subclass is an instance of a class at runtime? [duplicate]

You have to read the API carefully for this methods. Sometimes you can get confused very easily. It is either: if (B.class.isInstance(view)) API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at) or: if (B.class.isAssignableFrom(view.getClass())) API says: Determines … Read more

What’s the point of new String(“x”) in JavaScript?

There’s very little practical use for String objects as created by new String(“foo”). The only advantage a String object has over a primitive string value is that as an object it can store properties: var str = “foo”; str.prop = “bar”; alert(str.prop); // undefined var str = new String(“foo”); str.prop = “bar”; alert(str.prop); // “bar” … Read more

Why cast after an instanceOf?

Old code will not work correctly The implied cast feature is justified after all but we have trouble to implement this FR to java because of backward-compatibility. See this: public class A { public static void draw(Square s){…} // with implied cast public static void draw(Object o){…} // without implied cast public static void main(String[] … Read more

How to avoid ‘instanceof’ when implementing factory design pattern?

You could implement the Visitor pattern. Detailed Answer The idea is to use polymorphism to perform the type-checking. Each subclass overrides the accept(Visitor) method, which should be declared in the superclass. When we have a situation like: void add(Vehicle vehicle) { //what type is vehicle?? } We can pass an object into a method declared … Read more