The instanceof operátor a isInstance() Obidve metódy sa používajú na kontrolu triedy objektu. Ale hlavný rozdiel nastáva, keď chceme triedu objektov skontrolovať dynamicky, potom bude fungovať metóda isInstance(). Neexistuje žiadny spôsob, ako to môžeme urobiť pomocou operátora instanceof.
Metóda isInstance je ekvivalentná s operátorom instanceof. Metóda sa používa v prípade, že objekty sú vytvorené za behu pomocou odrazu. Všeobecná prax hovorí, že ak sa má typ skontrolovať za behu, použite metódu isInstance, inak je možné použiť operátor instanceof.
kruskalov algoritmus
Inštancia operátora a Obidve metódy isInstance() vracajú boolovskú hodnotu. Metóda isInstance() je metóda triedy Class v jazyku Java, zatiaľ čo instanceof je operátor.
Zvážte príklad:
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); } }
výstup:
true
Teraz, ak chceme skontrolovať triedu objektu za behu, musíme použiť isInstance() metóda.
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); } }
výstup:
true false true
JavaPoznámka: Operátor instanceof vyvolá chybu v čase kompilácie (nekompatibilné podmienené typy operandov), ak skontrolujeme objekt s inými triedami, ktoré nevytvára inštanciu.
pripojiť databázu java
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); } }
výstup:
9: error: incompatible types: Integer cannot be converted to String System.out.println(i instanceof String); ^
Musí si prečítať:
- nový operátor vs metóda newInstance() v jazyku Java
- Úvahy v Jave