If class B
and class C
extend class A
and I have an object of type B
or C
, how can I determine of which type it is an instance?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Use Object.getClass(). It returns the runtime type of the object.
We can use reflection in this case
Example:-
In this case you will get name of the class which object pass to
HttpServletRequest
interface refference variable.Multiple right answers were presented, but there are still more methods:
Class.isAssignableFrom()
and simply attempting to cast the object (which might throw aClassCastException
).Possible ways summarized
Let's summarize the possible ways to test if an object
obj
is an instance of typeC
:Differences in
null
handlingThere is a difference in
null
handling though:false
ifobj
isnull
(null
is not instance of anything).NullPointerException
obviously.null
becausenull
can be cast to any type!Notes
Class.getName()
should not be used to perform an "is-instance-of" test becase if the object is not of typeC
but a subclass of it, it may have a completely different name and package (therefore class names will obviously not match) but it is still of typeC
.Class.isAssignableFrom()
is not symmetric:obj.getClass().isAssignableFrom(C.class)
would returnfalse
if the type ofobj
is a subclass ofC
.You can use:
HTH. But I think most of the time it is no good practice to use that for control flow or something similar...
There is also an
.isInstance
method on the "Class
" class. if you get an object's class viamyBanana.getClass()
you can see if your objectmyApple
is an instance of the same class asmyBanana
via