Junior — Middle
Is it possible to determine the type of an object without using the typeof operator or similar methods?
sobes.tech AI
Answer from AI
Yes, it is possible to determine an object's type without using the typeof operator or similar methods, for example, by:
- Duck typing — if the object supports the required methods or properties.
- Using
instanceof(in Java) oris(in Kotlin) — they do not performtypeofbut check class membership. - In Android (Java/Kotlin), you can use the
getClass()method and compare it with the desired class.
Example in Java:
if (obj.getClass().equals(String.class)) {
// object is of type String
}
Thus, type can be determined by class comparison or interface checks without using typeof.