V tomto příkladu se naučíme určit třídu objektu v Javě pomocí metody getClass (), operátoru instanceof a metody isInstance ().
Abychom porozuměli tomuto příkladu, měli byste znát následující programovací témata Java:
- Třída Java a objekty
- Java instance operátora
Příklad 1: Zkontrolujte třídu objektu pomocí metody getClass ()
class Test1 ( // first class ) class Test2 ( // second class ) class Main ( public static void main(String() args) ( // create objects Test1 obj1 = new Test1(); Test2 obj2 = new Test2(); // get the class of the object obj1 System.out.print("The class of obj1 is: "); System.out.println(obj1.getClass()); // get the class of the object obj2 System.out.print("The class of obj2 is: "); System.out.println(obj2.getClass()); ) )
Výstup
Třída obj1 je: třída Test1 Třída obj2 je: třída Test2
Ve výše uvedeném příkladu jsme použili getClass()
metodu Object
třídy k získání názvu třídy objektů obj1 a obj2.
Chcete-li se dozvědět více, navštivte Java Object getClass ().
Příklad 2: Zkontrolujte třídu objektu pomocí operátoru instanceOf
class Test ( // class ) class Main ( public static void main(String() args) ( // create an object Test obj = new Test(); // check if obj is an object of Test if(obj instanceof Test) ( System.out.println("obj is an object of the Test class"); ) else ( System.out.println("obj is not an object of the Test class"); ) ) )
Výstup
obj je objekt třídy Test
Ve výše uvedeném příkladu jsme použili instanceof
operátor ke kontrole, zda je objekt obj instancí třídy Test.
Příklad 3: Zkontrolujte třídu objektu pomocí isInstance ()
class Test ( // first class ) class Main ( public static void main(String() args) ( // create an object Test obj = new Test(); // check if obj is an object of Test1 if(Test.class.isInstance(obj))( System.out.println("obj is an object of the Test class"); ) else ( System.out.println("obj is not an object of the Test class"); ) ) )
Výstup
obj je objekt třídy Test
Zde jsme použili isInstance()
metodu třídy Class
ke kontrole, zda je objekt obj objektem třídy Test.
isInstance()
Metoda funguje podobně jako instanceof
operátor. Je však upřednostňováno během doby běhu.