我了解到我可以使用对象的真实类型来定义使用哪个方法,如下所示:
[...]
Object foo = new String("hello");
[...]
bla(foo);
void bla(String x){
}
void bla(Integer x){
}
现在它应该采用 bla(String x) 方法,但我却收到编译器错误。我知道为什么:因为 foo
的类型当前是 Object
。我不确定我现在这样做是否正确,但我是这样理解的,Java将通过真实类型(或特定类型)选择方法,所以如果我将其向下转换为Object
,如果没有指定Object
方法,它将选择String
。
或者是在方法 void bla(Object x) 中通过 if(foo instanceof xxx)
确定类型的唯一方法?
PS:不要误解我的意思:我并不意味着我可以重载方法,我的意思是我想根据实际类型(而不是定义的类型)选择方法!
I learned that I can use the real type of a Object to define which Method is used, such like this:
[...]
Object foo = new String("hello");
[...]
bla(foo);
void bla(String x){
}
void bla(Integer x){
}
Now it should take the bla(String x)
method, but instead I get compiler error. I know why: because the type of foo
is currently Object
. I'm not sure if I do it currently right, but I understood it that way, that Java will choose the method by the real type (or specific type), so if I downcast it to Object
, it will choose the String
instead, if no Object
Method is specified.
Or is the only way to determinate the type by if(foo instanceof xxx)
in a method void bla(Object x)?
P.S.: dont get me wrong on this: I dont mean that I can overload methods, I mean that I want to choose the method based on the real type (not on the defined one)!
发布评论
评论(2)
对。在运行时调用哪个方法是在编译时选择的,并且编译器(通常)无法判断 foo 在运行时将具有哪种类型。
你不能“向下转换为对象”。不过,您可以向下转换为
String
。没错,如果您这样做,它将调用以
String
作为参数的bla
(如果foo< 则抛出
ClassCastException
/code> 不是String
)。这通常称为双 或多重调度,并且是一项不受支持的功能在爪哇。
如果您确实需要,请实现访问者模式。
顺便说一句,您所说的“定义类型”和“实际类型”通常分别称为静态类型和运行时类型。也就是说,
Object
是foo
的静态类型,而String
是它的运行时类型嗯>。Right. Which method is to be called at runtime, is chosen at compile-time, and the compiler can't (in general) tell which type
foo
will have in runtime.You can't "downcast to Object". You can downcast to a
String
though. And that's right, if you doit will invoke the
bla
that takes aString
as argument (and throw aClassCastException
iffoo
is not aString
).This is usually referred to as double or multiple dispatch, and is a feature not supported in Java.
Implement the visitor pattern if you really need this.
Btw, what you refer to as "defined type" and "real type" are usually referred to as static type and runtime type respectively. That is,
Object
is the static type offoo
, whileString
is it's runtime type.是的,你必须使用
instanceof
来获取真正的类型。 bla( Object ) 将始终调用 bla( Object o ) 方法。注意:基于“真实类型”选择方法仅适用于类方法。对象.方法(...)。如果存在的话,将根据“真实类型”选择方法(并向上直到对象)。
Yeah you have to use
instanceof
to get the realy type. bla( Object ) will always call the bla( Object o ) method.Note: Chosing method based on the "real type" is only possible for class methods. object.method( ... ). Will chose the method based on the "real type" if one exists (and go up till Object).