Re: Wrapper for multiple instanceof
Joshua Cranmer wrote:
getsanjay.sharma@gmail.com wrote:
Recently I have been trying to do a multiple instanceof and thought it
would be better to write a function than do those ugly || with
repeated instanceofs'.
Most instanceof's can be replaced with good OOP design.
public class MyInstance
{
public static boolean check(Object obj, String...classes) throws
Exception
{
boolean result = false;
for(String str : classes)
{
Class c = Class.forName(str);
result = result | (obj instanceof c);
if(result) break;
}
return(result);
Err.. ugly and uncompilable? The proper or for a boolean variable is ||
(short circuit boolean or) as opposed to | (bitwise or). This isn't C(++).
"|", in Java, is not just bitwise or. It is also a correct, but rarely
used, boolean operator, performing the same operation as "||" but always
evaluating the right hand side. See
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22.2
In this case, it makes no difference which of "|" or "||" is used. The
left hand side is always false so the right hand side has to be
evaluated even with "||".
However, it is a good idea to make a habit of using "||" unless there
is a reason to force evaluation of the right hand side when the left
hand side is true.
Patricia