ה מופע של מפעיל ו isInstance() שיטת שתיהן משמשות לבדיקת המחלקה של האובייקט. אבל ההבדל העיקרי מגיע כאשר אנו רוצים לבדוק את מחלקת האובייקטים באופן דינמי אז שיטת isInstance() תעבוד. אין שום דרך שנוכל לעשות זאת באמצעות מופע של אופרטור.
שיטת isInstance מקבילה לאופרטור instanceof. השיטה משמשת במקרה של יצירת אובייקטים בזמן ריצה באמצעות השתקפות. הנוהג הכללי אומר שאם יש לבדוק את הסוג בזמן ריצה, השתמש בשיטת isInstance אחרת ניתן להשתמש במופע של אופרטור.
המופע של מפעיל ו שיטת isInstance() מחזירה ערך בוליאני. שיטת isInstance() היא שיטה של class Class ב-java בעוד instanceof הוא אופרטור.
שקול דוגמה:
Java// Java program to demonstrate working of // instanceof operator public class Test { public static void main(String[] args) { Integer i = new Integer(5); // prints true as i is instance of class // Integer System.out.println(i instanceof Integer); } }
תְפוּקָה:
true
עכשיו אם אנחנו רוצים לבדוק את המחלקה של האובייקט בזמן הריצה אז אנחנו חייבים להשתמש isInstance() שִׁיטָה.
Java// Java program to demonstrate working of isInstance() // method public class Test { // This method tells us whether the object is an // instance of class whose name is passed as a // string 'c'. public static boolean fun(Object obj String c) throws ClassNotFoundException { return Class.forName(c).isInstance(obj); } // Driver code that calls fun() public static void main(String[] args) throws ClassNotFoundException { Integer i = new Integer(5); // print true as i is instance of class // Integer boolean b = fun(i 'java.lang.Integer'); // print false as i is not instance of class // String boolean b1 = fun(i 'java.lang.String'); // print true as i is also instance of class // Number as Integer class extends Number // class boolean b2 = fun(i 'java.lang.Number'); System.out.println(b); System.out.println(b1); System.out.println(b2); } }
תְפוּקָה:
true false true
Javaפֶּתֶק: instanceof אופרטור זורק שגיאת זמן קומפילציה (סוגי אופרנד מותנה לא תואמים) אם אנו בודקים אובייקט עם מחלקות אחרות שהוא לא מבצע מופע.
public class Test { public static void main(String[] args) { Integer i = new Integer(5); // Below line causes compile time error:- // Incompatible conditional operand types // Integer and String System.out.println(i instanceof String); } }
פלט:
9: error: incompatible types: Integer cannot be converted to String System.out.println(i instanceof String); ^
חובה לקרוא:
- אופרטור חדש לעומת שיטת newInstance() ב-Java
- הרהורים ב-Java