Detailed introduction and use of instanceof, use cases in actual projects

Keywords: Java Netty

instanceof is used to determine whether a specified object (an actual reference object instance) is an instance of a specified class or a subclass of a specified class?

usage

boolean result = object instanceof class

  • Object: Required option. Arbitrary object expression.
  • Class: Required option. Any object class.

If object is null, return false
If the object actually refers to an instance object of class or a subclass instance object of class, return true or false

Note: I have emphasized many instances of actual referenced objects. Most beginners don't pay attention to this.

public class Test {
    static class A{ }
    static class B extends A{ }

    public static void main(String[] args) {
        A a = new A();
        B b = new B();

        System.out.println( "a instanceof A Result:" + ( a instanceof A ) );
        System.out.println( "b instanceof A Result:" + ( b instanceof A ) );
        System.out.println();
        System.out.println( "a instanceof B Result:" + ( a instanceof B ) );
        System.out.println( "b instanceof B Result:" + ( b instanceof B ) );
        System.out.println();

        /*
        Be careful:
        Referring to an instance of a class with Object class objects is very common in practical applications.
        object instanceof class ,If the object instance actually refers to is the class instance object
         Or a subclass instance object of class returns true
        Note that the word "actual reference object instance" emphasizes the word "actual reference".
        */
        Object o = new A();
        System.out.println( "o instanceof A Result:" + ( o instanceof A ) );
        System.out.println( "o instanceof B Result:" + ( o instanceof B ) );
        System.out.println();

        o = new B();
        System.out.println( "o instanceof A Result:" + ( o instanceof A ) );
        System.out.println( "o instanceof B Result:" + ( o instanceof B ) );
        System.out.println();
    }
}

The results are as follows:

A instance of A results:
b instanceof A: true

a instanceof B: false
 b instanceof B: true

o instanceof A: true
 o instanceof B: false

o instanceof A: true
 o instanceof B: true

Most of the examples of instanceof articles on the Internet are similar to those above. However, in actual projects, it is only like this to judge the true and false, and then what?

In practical projects, instanceof is often used to determine whether an object is an instance of a class or its subclass, and if so, to force the object to be converted to the type of the class. As follows:

if( o instanceof A ){
	//o instanceof A is true, indicating that the object class that o actually refers to is a subclass of A or A, whereas A must be the object class or parent of O actually refers to.
	//Familiar with java basic grammar, we all know that subclass objects can be coerced into parent objects, so we can do the following coercion conversion.
	A a = A.class.cast(o);
	//...
}

Here's an example of instanceof actually being used in projects I use

	/**
	 * Receive message
	 */
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		try {
			Object object = e.getMessage();
			if (object == null){
				return;
			}
			if (!(object instanceof Collection)){
				return;
			}
			Collection<Object> c = Collection.class.cast(object);
			
			for (Object o : c) {
				if (org.jboss.netty.handler.timeout.IdleState.READER_IDLE.equals(o)) {
					ChannelBuffer buffer = new DynamicChannelBuffer(ByteOrder.BIG_ENDIAN, 8);
					buffer.writeByte(0);
					Channels.write(ctx, e.getFuture(), buffer);
				} else if (o instanceof Result1) {
					Result1 result1 = Result1.class.cast(o);
					//Processing receipt of result1 information
					//...
				}else if (o instanceof Result2) {
					Result2 result2 = Result2.class.cast(o);
					//Processing receipt of result2 information
					//...
				}
			}
			//...
		} catch (Throwable t) {
			if (channel.isConnected()) {
				channel.close();
			}
		}
	}

Last

There are many articles about instanceof on-line, but I still think it is necessary for me to write this article, because I always feel that there is something missing from those articles, either only definitions, or only test code, and some points needing attention are not pointed out. Of course, I may write some of the problems I just mentioned. If there is something wrong and what is missing, please let me know. I will correct and supplement them in time.

Posted by will_1990 on Sat, 27 Apr 2019 15:18:35 -0700