W tym przykładzie nauczymy się określać klasę obiektu w Javie za pomocą metody getClass (), operatora instanceof i metody isInstance ().
Aby zrozumieć ten przykład, należy znać następujące tematy dotyczące programowania w języku Java:
- Klasa i obiekty Java
- Instancja operatora Java
Przykład 1: Sprawdź klasę obiektu za 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()); ) )
Wynik
Klasa obj1 to: class Test1 Klasa obj2 to: class Test2
W powyższym przykładzie użyliśmy getClass()
metody Object
klasy, aby uzyskać nazwę klasy obiektów obj1 i obj2.
Aby dowiedzieć się więcej, odwiedź witrynę Java Object getClass ().
Przykład 2: Sprawdź klasę obiektu za pomocą operatora 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"); ) ) )
Wynik
obj jest obiektem klasy Test
W powyższym przykładzie użyliśmy instanceof
operatora do sprawdzenia, czy obiekt obj jest instancją klasy Test.
Przykład 3: Sprawdź klasę obiektu za 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"); ) ) )
Wynik
obj jest obiektem klasy Test
Tutaj użyliśmy isInstance()
metody klasy Class
do sprawdzenia, czy obiekt obj jest obiektem klasy Test.
isInstance()
Metoda działa podobnie do instanceof
operatora. Jednak jest to preferowane w czasie wykonywania.