Java-12.3 instanceof, isInstance, and isAssignableFrom

Source: Internet
Author: User

Java-12.3 instanceof, isInstance, and isAssignableFrom

This section describes three methods for detecting object types: instanceof, isInstance, and isAssignableFrom.

Example:

 

package com.ray.ch12;public class Test {public static void main(String[] args) {try {Class
  AClass1 = (Class
 ) Class.forName(com.ray.ch12.Sub);System.out.println(AClass1.newInstance() instanceof Sub);System.out.println(AClass1.newInstance() instanceof Father);System.out.println(AClass1.isInstance(new Sub()));System.out.println(AClass1.isInstance(new Father()));System.out.println(AClass1.isAssignableFrom(Sub.class));System.out.println(AClass1.isAssignableFrom(Father.class));} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class Father {}class Sub extends Father {}

Output:

 

True
True
True
False
True
False

 

1. Note the following when reading the above Code:

(1) The instanceof parameter is a class

(2) parameters following isInstance are class objects.

(3) The parameter following isAssignableFrom is the Class Object of the Class.

These three methods are used to detect object types.

 

2. Note the following points from the output result:

(1) instanceof supports upward transformation, so the above AClass1 is also Father Class type

(2) isInstance and isAssignableFrom do not support upward transformation. Therefore, the output of AClass1 can only point to Sub, but cannot recognize Father.

 

Summary: This chapter mainly describes the methods instanceof, isInstance, and isAssignableFrom for the three object types, as well as the corresponding notes.

 

 


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.