Instanceof operator usage

Source: Internet
Author: User

A instanceof B;

 

A must be a specific instance, and B must be a type (or interface ).

 

B cannot be a wildcard parameter.

 

If a determines the specific type during compilation, A must be able to convert (B) A to B. Otherwise, the compiler reports an error.

 

If a cannot be converted to B, you can (object) A instanceof B.

 

If a is actually running, there is no such limit.

 

In the specific example, the following information is obtained on the Forum:

Package instan;

Import java. util. List;

Public class test {

Public static void main (string [] ARGs ){
// The exact type of the reference type returned by GetObject () cannot be determined during compilation. The following two statements can be compiled
System. Out. println (GetObject () instanceof object );
System. Out. println (GetObject () instanceof string );
System. Out. println (GetObject () instanceof test );

// The type can be determined during compilation. If cast can be used, the compilation succeeds; otherwise, the compilation fails.
Test test = new test ();
System. Out. println (test instanceof test); // OK
System. Out. println (test instanceof object); // OK
// System. Out. println (test instanceof string); // error, you can use the following method
System. Out. println (object) test instanceof string );

// Notes related to generics
// List is a generic type. If no generic parameter is specified, the compilation is successful.
System. Out. println (test instanceof list );
// If you do not limit the type limit, compile
System. Out. println (test instanceof list <?> );

// Specify generic parameters. The type can be determined during compilation. If cast is not supported, compilation fails.
// System. Out. println (GetObject () instanceof list <Test>); // Error
// System. Out. println (test instanceof list <Test>); // Error
}

Public static object GetObject (){
Return new test ();
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.