How to tell the class of an object?
Given a method that takes a specific supertype as a parameter. Is there a way, within this method, to determine the actual class of the object that was passed to it? That is, if a subtype of a valid parameter was actually accepted, is there a way to know what type it is? If this is not possible, can someone explain why not (in terms of language design)? Thanks to
Update: just to make sure I'm free
Context: MySubType extends MyType
void doSomething(MyType myType) {
//determine if myType is MyType OR one of its subclasses
//i.e. if MySubType is passed as a parameter, I know that it can be explicitly
//cast to a MySubType, but how can I ascertain that its this type
//considering that there could be many subclasses of MyType
}
Since the method signature specifies the parameter as MyType
, then how to determine if an object is indeed a subtype MyType
(and which).
a source to share
If you look at the javadoc for the Object class, you will find that each object supports getClass()
. It is an Class
object and you can navigate from there.
If an object MyType
, then getClass() == MyType.class'. If the object is a superclass, then
getClass ()! = MyType.class`.
There are only these possibilities. If the parameter type, a MyType
, MyType
is a class and not an interface, then either an object MyClass
or a subtype. If it is a subtype, then getClass()
returns Class
for the subtype. You can use the API Class
to learn it.
You can, of course, use reflection to explore the type hierarchy. You can request a MyType.class
list of its direct subclasses to and from there and have a fine old time. But you don't need to.
a source to share
Yes, there is a built-in reflective API called Trail that allows you to check the types of any instance of a class. A method getClass()
that inherits from a class Object
will give you an object Class
that you can inspect. A good starting point is the Sun's Tutorial Trail .
a source to share
I am assuming that MyType is the type of the superclass, right?
1 / If you just want to know that this is not the case for your superclass type: you can check
if (m.getClass() != MyType.getClass())
2 / If you want to check if m belongs to a specific subclass, I don't think there is a way, you need to write it as
if (m.getClass() == MySubType) {
}
or you can use:
if (!(m instanceof MySubType)) {
}
a source to share