Ebben a példában megtanuljuk meghatározni egy objektum osztályát a Java-ban a getClass () metódus, az instanceof operátor és az isInstance () módszer segítségével.
A példa megértéséhez ismernie kell a következő Java programozási témákat:
- Java osztály és objektumok
- Operator Java példánya
1. példa: Ellenőrizze az objektum osztályát a getClass () használatával
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()); ) )
Kimenet
Az obj1 osztálya: class Test1 Az obj2 osztálya: Class2 teszt
A fenti példában getClass()
az Object
osztály metódusát használtuk az obj1 és obj2 objektumok osztálynevének megszerzésére.
További információkért látogasson el a Java Object getClass () oldalra.
2. példa: Ellenőrizze az objektum osztályát az instanceOf operátorral
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"); ) ) )
Kimenet
obj a teszt osztály objektuma
A fenti példában az instanceof
operátort használtuk annak ellenőrzésére, hogy az objektum objektum-e a Test osztály példánya.
3. példa: Ellenőrizze az objektum osztályát az isInstance () használatával
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"); ) ) )
Kimenet
obj a teszt osztály objektuma
Itt isInstance()
az osztály metódusát használtuk Class
annak ellenőrzésére, hogy az objektum objektum-e a Test osztály objektuma.
A isInstance()
módszer az instanceof
operátorhoz hasonlóan működik . Előnyös azonban a futási idő alatt.