Jak określić klasę obiektu?

Jeśli klasa B i klasa C rozszerzają klasę A i mam obiekt typu B LUB C, Jak mogę określić, jakiego typu jest to instancja?

Author: Lii, 2009-02-12

11 answers

if (obj instanceof C) {
//your code
}
 827
Author: IAdapter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-12 15:37:13

Użyj Obiektu.getClass () . Zwraca typ runtime obiektu.

 376
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-17 11:01:54

Przedstawiono wiele prawidłowych odpowiedzi, ale jest jeszcze więcej metod: Class.isAssignableFrom() i po prostu próba rzucenia obiektu(co może rzucić ClassCastException).

Możliwe sposoby podsumowania

Podsumujmy możliwe sposoby sprawdzenia, czy obiekt obj jest instancją typu C:

// Method #1
if (obj instanceof C)
    ;

// Method #2
if (C.class.isInstance(obj))
    ;

// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
    ;

// Method #4
try {
    C c = (C) obj;
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

// Method #5
try {
    C c = C.class.cast(obj);
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

Różnice w obsłudze null

Istnieje różnica w obsłudze null:

  • w pierwszych 2 metodach wyrażenia oceniają na false Jeśli obj jest null (null nie jest niczym).
  • trzecia metoda rzuciłaby NullPointerException oczywiście.
  • czwarta i piąta metoda wręcz przeciwnie akceptują null, ponieważ null można rzucać na dowolny typ!

Aby pamiętać: null nie jest instancją dowolnego typu, ale może być rzucona do dowolnego typu.

Uwagi

  • Class.getName() nie powinien być używany do wykonywania testu "is-instance-of" , jeśli obiekt nie jest typu C ale jej podklasa może mieć zupełnie inną nazwę i pakiet (dlatego nazwy klas oczywiście się nie zgadzają), ale nadal jest typu C.
  • Z tego samego powodu dziedziczenia Class.isAssignableFrom() nie jest symetryczna:
    obj.getClass().isAssignableFrom(C.class) zwraca false, Jeśli typ obj jest podklasą C.
 180
Author: icza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-01 12:25:25

Możesz użyć:

Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object

HTH. Ale myślę, że większość czasu nie jest dobrą praktyką, aby używać tego do sterowania przepływem lub coś podobnego...

 32
Author: Johannes Weiss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-12 15:22:57

Każde użycie którejkolwiek z zaproponowanych metod jest uważane za zapach kodu, który opiera się na złym projekcie OO.

Jeśli twój projekt jest dobry, nie powinieneś używać getClass() lub instanceof.

Każda z sugerowanych metod wystarczy, ale należy o tym pamiętać, projektowo.

 23
Author: Yuval Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-12 15:25:53

W tym przypadku możemy użyć odbicia

objectName.getClass().getName();

Przykład:-

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String name = request.getClass().getName();
}

W tym przypadku otrzymasz nazwę klasy, którą obiekt przekazuje do zmiennej refference interfejsu HttpServletRequest.

 16
Author: user1884500,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-03 05:24:42

Istnieje również .isInstance metoda na klasie " Class". jeśli uzyskasz klasę obiektu poprzez myBanana.getClass(), możesz sprawdzić, czy twój obiekt myApple jest instancją tej samej klasy co myBanana poprzez

myBanana.getClass().isInstance(myApple)
 13
Author: Andreas Petersson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-29 18:21:26

Sprawdzanie za pomocą isinstance() nie wystarczy, jeśli chcesz wiedzieć w czasie wykonywania. użycie:

if(someObject.getClass().equals(C.class){
    // do something
}
 2
Author: Alon Gouldman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-01 09:47:09

Użyłem Java 8 generics, aby dowiedzieć się, jaka jest instancja obiektu w czasie wykonywania, zamiast używać switch case

 public <T> void print(T data) {
    System.out.println(data.getClass().getName()+" => The data is " + data);
}

Przekaż dowolny typ danych, a metoda wyświetli typ danych, który przekazałeś podczas jej wywołania. eg

    String str = "Hello World";
    int number = 10;
    double decimal = 10.0;
    float f = 10F;
    long l = 10L;
    List list = new ArrayList();
    print(str);
    print(number);
    print(decimal);
    print(f);
    print(l);
    print(list);

Poniżej znajduje się wyjście

java.lang.String => The data is Hello World
java.lang.Integer => The data is 10
java.lang.Double => The data is 10.0
java.lang.Float => The data is 10.0
java.lang.Long => The data is 10
java.util.ArrayList => The data is []
 1
Author: Saurabh Verma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-14 06:35:49

Używam funkcji blow w mojej klasie Generalitils, sprawdź czy może się przydać

    public String getFieldType(Object o) {
    if (o == null) {
        return "Unable to identify the class name";
    }
    return o.getClass().getName();
}
 0
Author: Ahmed Salem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-24 06:25:50

Możesz użyć getSimpleName () .

Powiedzmy, że mamy obiekt: pies d = Nowy Pies(),

Możemy użyć poniższego polecenia, aby uzyskać nazwę klasy: Dog. Np.:

D. getClass().getSimpleName(); // return String 'Dog'.

PS: D. getClass () poda ci Pełną Nazwę obiektu.

 0
Author: Frank Liu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-03 11:13:46