Re: Wrapper for multiple instanceof
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(++).
correct code:
for (String str : classes) {
Class<?> c = Class.forName(str);
if (c.isInstance(obj))
return true;
}
return false;
Even better would be to redeclare check as:
public static boolean check(Object obj, Class... classes)
circumventing the reflection needed.
}
public static void main(String args[]) throws Exception
{
String str = "hello";
String classes[] = {"String", "StringBuffer"};
System.out.println(MyInstance.check(str, classes));
Use varargs properly:
System.out.println(MyInstance.check(str,"String","StringBuffer"));
Or, using redefined check:
System.out.println(MyInstance.check(str,String.class,StringBuffer.class));
}
}
I do very well realize that the instanceof operator requires a TYPE on
its RHS, but I can't seem to find out how to convert the class name
string to a type?
By the nature of the underlying bytecode, the RHS of the instanceof
operator has to be known at compile time, rendering the ability to do
runtime loading impossible without using reflection. You started using
the Class class but seemed to have dropped off before getting to the
important part (it does have a method named instanceOf, after all).
Is such kind of thing even possible here or doing multiple || with
instanceofs' is the only way to go?
See above. I recommend, however, that the code be redesigned to avoid
using instanceof's if possible.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth