简体   繁体   中英

Determining the type of an object in java

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM