The esimerkki operaattori ja isInstance() menetelmää molempia käytetään kohteen luokan tarkistamiseen. Mutta suurin ero tulee, kun haluamme tarkistaa objektien luokan dynaamisesti, jolloin isInstance() -menetelmä toimii. Emme voi mitenkään tehdä tätä instanceof-operaattorilla.
IsInstance-menetelmä vastaa instanceof-operaattoria. Menetelmää käytetään, jos objektit luodaan ajon aikana heijastuksen avulla. Yleinen käytäntö sanoo, että jos tyyppi on tarkistettava ajon aikana, käytä isInstance-menetelmää, muuten instanceof-operaattoria voidaan käyttää.
Operaattorin esimerkki ja isInstance() -menetelmä palauttaa loogisen arvon. isInstance()-metodi on luokan Class menetelmä javassa, kun taas instanceof on operaattori.
Harkitse esimerkkiä:
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); } }
Lähtö:
virhe: pääluokkaa ei löytynyt tai ladata
true
Nyt jos haluamme tarkistaa objektin luokan ajon aikana, meidän on käytettävä isInstance() menetelmä.
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); } }
Lähtö:
true false true
JavaHuomautus: instanceof-operaattori heittää käännösaikavirheen (yhteensopimattomat ehdolliset operandityypit), jos tarkistamme objektin muiden luokkien kanssa, joita se ei instantoi.
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); } }
Lähtö:
9: error: incompatible types: Integer cannot be converted to String System.out.println(i instanceof String); ^
Täytyy lukea:
- uusi operaattori vs newInstance() -metodi Javassa
- Heijastuksia Javassa