Instanceof operator

Hello
I have a flow that if an object of class b then I want a method executed and if of class a then a different method. The two methods are in both classes. I have tried the following with errors everywhere.
if ( objA instance of Class B)
objA.method2(int, int, File);
objA.method1(float, float,File);
What is the more generic technique of calling different overloaded methods depending on object type? tia.

Hello
I have a flow that if an object of class b then I
want a method executed and if of class a then a
different method. The two methods are in both
classes. I have tried the following with errors
everywhere.
if ( objA instance of Class B)
objA.method2(int, int, File);
objA.method1(float, float,File);
What is the more generic technique of calling
different overloaded methods depending on object
type? tia.using "instanceof" is generally a good indicator that some serious refactoring's needed
An object should know how it must behave; other objects shouldn't look at it and take appropriate action according to what they see; they just tell the object "do your thing, I don't care what concrete type you are, and even less how you do it" and know it can do it, because it is declared so in its interface
Visitor pattern, maybe ?
public interface SuperType {
    public void accept(Visitor visitor);
public class Visitor {
    public void visit(A visited) {
        visited.method1(args1);
    public void visib(B visited) {
        visited.method2(args2);
public class A implements SuperType {
    public void accept(Visitor visitor) {
        visitor.visit(this);
public class B implements SuperType {
    public void accept(Visitor visitor) {
        visitor.visit(this);
}

Similar Messages

  • Is the 'instanceof' operator discouraged ?

    Hi,
    I have heard that the instanceof operator is not recommended and should be used only as a last resort. Can someone throw some light into it ? is there an alternative ?
    thanx and regards

    hi,
    thanx for the response.
    well, the BaseException and its subclasses belong to a different applicaiton, and my application calls this application thru remote interface.
    For each of the 5 sub-exceptions, we need to log a different message, and then propogate the same to our client.
    There is too much code repetetion-- My session bean has 10 methods, each of these catch the 5 sub-classes, log a message and throw a new exception.
    To avoid code repetetion, i ll catch the BaseException in each of the 10 methods of session bean, and then in the catch block, i ll call a method say -- handleExeption, which will identify the type of exception and take the action that were taken earlier by the multiple catch blocks.
    Now, I need to use the instanceof operator to identify the specific type of exception. Will it be recommended practice ?
    thanx and regards

  • Avoiding using instanceof operator

    I've heard that using the instanceof operator isn't such a great code technique, and since I'm in the design phase, I feel like I should be able to avoid this. Right now, part of my design requires use of the instanceof operator as well as casting.
    Let's say you have a common notifier interface and two abstract classes which extend from this interface:
    com.example.Notifier Interface:
    public void doNotify(Notification notif, List notifiables);
    public boolean canSend(Notification notif, Notifiable person);
    com.example.SerialNotifier (abstract)
    public void doNotify(Notification notif, List people)
        for (Iterator itList = people.iterator(); itList.hasNext();)
             Notifiable person = (Notifiable)itList.next();
             doNotify(person, notif);
    public abstract doNotify(Notification notif, Notifiable person);
    com.example.MulticastNotifier (abstract)
    public abstract void doNotify(Notification notif, List notifiables);MulticastNotifier purposefully doesn't define a way to send a message to a single person, so that developers don't implement a non-multicast solution for a multicast protocol.
    Here's the part that seems to require an "instanceof" clause. Now let's say you have a list of Notifiers. The list of notifiers is mixed, containing both Serial and Multicast Notifiers. Before you send out the notification, you need to filter the list (because for example, someone doesn't want to be notified at all):
        for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
             Notifier notifier= (Notifier)itNotifiers.next();
             List buildPeopleList = new ArrayList();
             for (Iterator itPeople = people.iterator(); itPeople.hasNext())
                   Notifiable person= (Notifiable)itPeople.next();
                   if (notifier.canSend(person, notification))
                           if (notifier instanceof MulticastNotifier)
                                  buildPeopleList.add(person);
                           } else
                                   SerialNotifier serialNotif = (SerialNotifier)notifier;
                                   serialNotif.doNotify(notification, person);
             if (notifier instanceof MulticastNotifier)
                      notifier.doNotify(notification, buildPeopleList)
        }Is this bad design? Another option is to just iterate through the list essentially twice, but this is of course, less efficient for the serial notifier case:
        for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
             Notifier notifier= (Notifier)itNotifiers.next();
             List buildPeopleList = new ArrayList();
             for (Iterator itPeople = people.iterator(); itPeople.hasNext())
                   Notifiable person= (Notifiable)itPeople.next();
                   if (notifier.canSend(person, notification))
                           buildPeopleList.add(person);
             notifier.doNotify(notification, buildPeopleList);
        }Any suggestions?

    I'm not sure what you mean. I moved a loop from your
    code to a different class. AFAICT, it's a
    one-for-one. My solution has the same number of
    iterations as yours.Yeah, your code is actually missing a loop, because, as I explained earlier, the design supports filtering at both a parent notifier and a child notifier. To filter, it needs to loop through the list of people
    So, your code actually will look like: (forgive me, doing code in a textarea is kinda a pain)
    public void ParentNotifier implements Notifier
    // member var for simplicity
    protected Filter myFilter = new ExampleFilter();
    protected List notifiers = // list of notifiers
    public void doNotify(Notification n, List people)
      List intermediateList= new ArrayList();
      for (Iterator itPeople = people.iterator(); itPeople.hasNext();)
            Notifiable person = (Notifiable); itPeople.next()
            if (myFilter.canSend(n, person) // parent's filter
                 intermediateList.add(person);
       for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
                    Notifier notif = (Notifier)itNotifiers.next();
                    notif.doNotify(n, intermediateList); // 2nd loop is in here where additional filtering takes place
    }If you assume a serial notifier, you don't need this additional iteration:
    public void ParentNotifier implements Notifier
    // member var for simplicity
    protected Filter myFilter = new ExampleFilter();
    protected List notifiers = // list of notifiers
    public void doNotify(Notification n, List people)
      for (Iterator itPeople = people.iterator(); itPeople.hasNext();)
            Notifiable person = (Notifiable); itPeople.next()
            if (myFilter.canSend(n, person) // parent's filter
                 for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
                         Notifier notif = (Notifier)itNotifiers.next();
                         // PROBLEM HERE: assumes serial notifier
                         notif.doNotify(n, person); // child will do own filtering
    }Edit: Corrected logic error in code

  • Java InstanceOf operator

    I am writing a program that runs on a simulated network, that exposes my data to potential corruption. So, if I send an object across the network and some of the bytes in that object get corrupted will the instanceof operator still recognize that object as a member of a particular class even though some of the data is corrupted, or does it depend on which actual bytes are corrupted?

    When an object is serialized part of what's sent is the name of the class, and that's all that determines what class of object it will attempt to reconstruct..
    If you're using an unreliable connection stream then you should probably add a CRC check of some kind. Most of the channels you migh use have that built in.

  • Instanceof operator, please help!

    I am reading the codes written by others. I am confused on instanceof operator here.
    (A instanceof B) where A and B are interfaces. I found a definition in a book such that the
    instanceof operator returns true or false based on whether the object is an instance of the named
    class or any of that class's subclass. However, I didn't find the relationship between A and B is
    established in the codes. In this case, I wonder if instanceof operator can still be used because I am thinking that it will always evaluate to be false.
    Thank you for your help!
    Cathy

    The instanceof operator can always be used - a return value of false is still a valid return value!
    However, when it comes to interfaces it is possible for a class to implement both interfaces even though there may be no direct relationship between those interfaces.
    Have a look at this:
    public interface MyInterface
    public interface YourInterface
    public class MyClass implements MyInterface, YourInterface
    }There is no relationship between the two interfaces but I can still do this:
    public void check(MyInterface myObj)
      if(obj instanceof YourInterface)
        YourInterface yourObj = (YourInterface)myObj;
        System.out.println("Woo hoo - an instance of MyInterface that's also an instance of YourInterface!");
    }Essentially the instanceof operator is asking if the value passed can be cast to something else for the method to use it more specifically.
    There could be classes other than MyClass that implement both interfaces, particularly if a system is designed to be flexible.
    I hope this makes sense!

  • About instanceof operator

    Example1:Suppose class SubComp extends Component. There has an instance of SubComp calls subCompInstance.When I wrote:subCompInstance instanceof String will compile fail�Bwhy?
    Example2:java.sql.Connection fobjConn; fobjConn instanceof String will compile success.
    Could you tell me what restrice of the second operand?
    Thank you very much!

    from JLS 15.20.2
    "If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true. .."
    basically what it says is, if the type of the reference you arre using can never be an instance of the type you mentioned, the compiler should generate error. so this will not compile
    Component c = create a component
    boolean b =(c instanceof String)
    but this will
    Object c = create a component
    boolean b = (c instanceof String)
    since, in the second case c has the type Object which, depending on the actual class, may be casted to String at runtime.
    Hope it clarifies.

  • Instanceof operator treatment

    Hi I am new bie in java,
    Following is my code.
    public class Test {
        public static void main(String[] args) {
            Test test = new Test();
            System.out.println(test instanceof T);
            System.out.println(test instanceof I);
    interface I {
    class T {
    }Compiler shows error at line System.out.println(test instanceof I);. but not at System.out.println(test instanceof T);.
    If compiler can check that there is no IS A relationship between class Test & T then why it can't chek same for interface reference type.
    Can you please explain the rationale?

    Hi I am new bie in java,
    Following is my code.
    public class Test {
    public static void main(String[] args) {
    Test test = new Test();
    System.out.println(test instanceof T);
    System.out.println(test instanceof I);
    interface I {
    class T {
    }Compiler shows error at line
    System.out.println(test instanceof I);.
    but not at System.out.println(test instanceof
    T);.
    If compiler can check that there is no IS A
    relationship between class Test & T then why it can't
    chek same for interface reference type.
    Can you please explain the rationale?I guess, since all the classes are derived from "Object" base class, thats y the classes (Test & T) are being compared. But the interface does not extend from the Object class..

  • Incompatible types error in instanceof operator

    inconvertible types error. I have no idea why???
    class A
    class B
    public class Test2
    public static void main(String[] args)
    {     A a = new A();
         B b = new B();
    if (b instanceof A) System.out.println("b is child of A");
         if (a instanceof B) System.out.println("a is child of B");

    The compiler can tell that a isn't an instance of B and b isn't an instance of A. It doesn't need to wait until runtime. So it doesn't waste any time, it tells you that.

  • Instanceof operator question

    Can you use instance of (successfully) on interfaces and abstract classes?
    I am confused because if class A implements interface B (or extends abstract class B) it is a type of B but it is not an instance of B, since interfaces/abstract classes cannot be instantiated.

    Sorry, the reason I ask is because on weekdays I have limited internet time so if I ask it here I can work on my projects and get the answer without taking time away from working on my project. Thanks for the answers.

  • How to determine the type of the jobject... similar to instanceof

    hi,
    I would like to know how to determine the jobject reference of an instance is of which class.
    this is something similar to instanceof we use in java.
    is there any thing like 'instanceof' in JNI. if there how to use it?
    i got this as objective question for which answers were(i do not remember exactly)
    1.instanceof
    2.assignedto
    i could nt het much help in googling.
    thanks in advance

    Hi
    The JNI provides a native version to the java instanceof operator, this function takes two arguments
    an object refrence and a class refrence and reports JNI_TRUE.
    jclass myclass = env->FindClass("your class name");
    if(env->IsInstanceOf(obj,myclass) == JNI_TRUE)
    // obj is of type myclass
    }Regards
    pradish

  • Dynamic class cast and instanceof

    I am looking for a way to dynamically test an object for being of a specific class. The instanceof operator can only be used with literally named classes I understand. So you cannot have something like boolean checkClass( Object o, Class c ) {
       return o instanceof c;
    } Is there any way to do something like this by use of the reflection API? The point is that instanceof only works statically, the reference type being tested for being specified at compile time. The question is whether it can be done with a reference type being specified at run-time, ie dynamically.

    There is a collection of parameters of various types, which is passed to some client module.
    There should be a, say 'checkParam' method for the client, which checks for existence of a certain parameter by its name, and also specified which class the parameter should have. So it should be called like
    checkParam( params, "paramName", String.class )I wanted to avoid hard-coded types, but have the class specified as an argument to this method. I feel like there should be some way to accomplish that. What swingfreak intended may be a way.

  • Instanceof in ejb ql

    Hi
    Am I the only one that noticed the lack of instanceof operator in EJB QL?
    Suppose I have "class B extends A", and I want to select the A entities which are not A, for instance. I'd expect to be able to do:
    "from A a where not(a instanceof B)"
    There are numerous other usages I have encountered and had to workaround it.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Amit Kasher

    select a from A a where a not in (select b from B b) might work.

  • Dynamic equivalent of the Java language CAST operator

    Hello,
    Here is what I want to do:
    I have an Object that contain "something" (I don't know at compilation time). And I want to do this call:
    Object myObject = new String("Hello");
    myMethod (myObject);
    having declared these:
    public void myMethod (Integer dInt);
    public void myMethod (String sString);
    I want the second method to be called. How can I do that?
    I'm looking for something like a dynamic equivalent of the Java language cast operator:
    ??? myMethod ( (myObject.getClass())myObject ); ???
    or ?? myMethod ( (myObject.castTo(myObject.getClass()) ) ; ??
    Thanks.

    How 'bout using the instanceof operator?
    Like this:
    public myMethod(Object obj)
    if (obj instanceof String)
    //do String stuff
    else if (obj instanceof Integer)
    //do Integer stuff
    }

  • Instanceof failed while getClass().getName() is right

    Hi, everyone
    What may cause instanceof operator returns false while getClass().getName() returns the right class name?
    I get a list through JMX. At first, I print the type of elements in the list. It is what I want. But ClassCastException is raised when I want to cast the element into the required type. With great supprise, I check the element with instanceof operator, it returns false. I am puzzled. Here are source codes:
    String[] type = {"para"};
    String[] sig = {"java.lang.String"};
    List list = (List) server.invoke(ManagerMBean.OBJECT_NAME, "getAppsbyType", type, sig); // get objects in the MBeanServer
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
    Object obj = iter.next();      
    System.out.println(obj.getClass().getName()); // the ouptut is A
    if(obj instanceof A ) {
         System.out.println("....................................it is A");
    }else{
         System.out.println("....................................it is not A"); // it is executed
    A a= (A) obj; // ClassCaseException occured
    Does anybody encounter similar problem?
    Any help is appreciated!

    What may cause instanceof operator returns false while
    getClass().getName() returns the right class name?The object passed to instanceof is of a type that was loaded in a different classloader than the calling object's class.

  • How fast is instanceof?

    How expensive is an instanceof operation? Is it in the order of simple arithmetic, or of reflection? Does it vary much?

    How expensive is an instanceof operation? Is it in
    the order of simple arithmetic, or of reflection?
    Does it vary much?Between the two, and yes. It's rarely going to be as slow as reflection, but when you get a "hit" it's practically as fast as arithmetic.
    So performance is rarely a reason to avoid "sanity tests" in code (remember, instanceof is essentially a check for != null as well as the type of the object).
    Try the following code snippet:
    import java.util.*;
    public class iof
       public static void main(String[] argv)
          int c = 1000000;
          List content = new ArrayList(c);
          for(int i = 0; i < c; i++ )
             content.add(new String("" + i));
          boolean ignoreState = false;
          Iterator i;
          long start = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
          // Instance of (miss)
             ignoreState = (o instanceof List);
          long middle1 = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
          // Instance of (hit)
             ignoreState = (o instanceof String);
          long middle2 = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
          // Instance of (arithmetic)
             ignoreState = ((2 + 2) > 3);
          long middle3 = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
             ignoreState = ( o.getClass().getName().equals(STRINGNAME) );
          long end = new Date().getTime();
          System.out.println("Instanceof (Miss) : " + (middle1 - start) + "ms");
          System.out.println("Instanceof (Hit)  : " + (middle2 - middle1) + "ms");
          System.out.println("Arithmetic        : " + (middle3 - middle2) + "ms");
          System.out.println("Reflection        : " + (end - middle3) + "ms");
       private static String STRINGNAME = "java.lang.String";
    }

Maybe you are looking for