简体   繁体   English

在Java中确定对象的类型

[英]Determining the type of an object in java

Say I have the following java code: 假设我有以下Java代码:

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. 请注意,我不是在说实例化对象的类型(在此为ArrayList),而是在表达式左侧的类型,因此在上面的示例中,myObj的对象为myObj, List的实例为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 . 左侧使用的类型不是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() . 例如,如果它是一个字段(静态或实例),则可以获取适当的Field引用,可以使用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. 调用myList.getClass()或类似的操作将无法执行您想要的操作,因为这将处理myList ,而不是变量本身。

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() . 您可以通过调用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. 当调用f(var) ,编译器将使用var的静态类型来调用正确的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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