0

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,

2 Answers 2

4

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 Field reference, you can ask for the type using Field.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 of myList, not the variable itself.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks Jon. To sum up: in order to determine the dynamic type, I use getClass(). In order to determine the static type I have to resort to reflection and more specifically Field.getType(). Is this correct?
Never mind local variables. Instance variables will suffice. I was not trying to achieve anything particular. Just getting clear some concepts...
3

The "left-hand side" type is called the static type.

The "right-hand side" type is called the dynamic type.

You can determine the dynamic type by calling var.getClass().

One way to determine the static type is by using function overloads:

public static void f(Object var) { ... }
public static void f(List var) { ... }

When you call f(var), the compiler will use the static type of var to call the correct function.

3 Comments

sure: myObj.appropriateMethod()==Object.class or myList.appropriateMethod()==List.class
getClass will help me with the dynamic type but not the static type won't it?
That's an interesting way of getting the static type without reflection! Thanks to you aix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.