Say I have the following java code:
Object myObj = new ArrayList();
List myList = new ArrayList();
I would like to know how to determine which class or interface a given object is typed with.
Note that I am not talking of the type the object was instanciated from (here ArrayList) but rather the type on the left-hand side of the expression so that would be in the example above Object for myObj and List for myList.
How do I call this “left-hand side” type in proper parlance?
Also, how do I call the “right-hand side” type?
How do I determine programmatically what is this “left-hand side” type?
Regards,
The type used on the left-hand side is not the type of an object. It’s the type of a variable. (The static or compile-time type.)
It’s worth differentiating between a variable and an object – a variable has a name, a type and a storage location. The storage location contains value compatible with the type of the variable.
Now to find the type of a variable at execution time, you’d need some sort of reference to the variable itself as a variable. For example, if it’s a field (static or instance) you can fetch the appropriate
Fieldreference, you can ask for the type usingField.getType().If it’s a local variable you’ll find it a bit harder. If you can explain what you’re trying to achieve (rather than the mechanism you think will help you achieve it) we may be able to help more.
Calling
myList.getClass()or anything like that will not do what you want, because that will deal with the value ofmyList, not the variable itself.