[英]How do I make sense of this Java syntax, a class name in parentheses before a method name?
I'm seeing this syntax and can't understand what it means.我看到了这种语法,但无法理解它的含义。 It doesn't look like a regular object instantiation.
它看起来不像常规的 object 实例化。 The 'new' keyword isn't there and the class name is put in parenthesis... then there's a method call at the end.
'new' 关键字不存在,并且 class 名称放在括号中......然后最后有一个方法调用。
MyClass myObj = (MyClass) someMethod(arg);
In Java,在 Java 中,
someMethod(arg)
is a call of a method named someMethod
with a single parameter arg
.是调用带有单个参数
arg
的名为someMethod
的方法。
All methods (except void
ones) return a value.所有方法(除了
void
方法)都返回一个值。 The type of the return value is part of method definition.返回值的类型是方法定义的一部分。 In your case, we don't know what the
someMethod
returns (because you didn't provide its definition), but we can assume it is not void
.在您的情况下,我们不知道
someMethod
返回什么(因为您没有提供它的定义),但我们可以假设它不是void
。
The expression表达方式
(MyClass) obj
is a type cast , which tells the compiler to treat obj
as if it was of type MyClass
.是一种类型转换,它告诉编译器将
obj
视为MyClass
类型。 During compilation, compiler checks that the definition of obj
is compatible with MyClass
, and if it is, it allows you to treat it like one.在编译期间,编译器会检查
obj
的定义是否与MyClass
兼容,如果是,则允许您将其视为一个。 During run time, Java virtual machine checks that the actual object obj
is actually instance of class MyClass
.在运行时,Java 虚拟机检查实际的 object
obj
实际上是 class MyClass
的实例。 If it is not, it will throw a ClassCastException
.如果不是,它将抛出
ClassCastException
。
Typically, type casts are used to "upgrade" how the compiler sees an object into something more specific.通常,类型转换用于将编译器如何将 object “升级”为更具体的内容。 For example, if a pet shop by definition sells
Animal
s, and you ordered a Hamster
, then you can reasonably assume thet what you get is not just an Animal
, but a Hamster
(assuming Hamster extends Animal
).例如,如果根据定义,一家宠物店出售
Animal
,而您订购了Hamster
,那么您可以合理地假设您得到的不仅仅是Animal
,而是Hamster
(假设Hamster extends Animal
)。
Now, put this together and you get a type cast applied to a method return value.现在,把它们放在一起,你会得到一个应用于方法返回值的类型转换。
There is a method somewhere that is returning an object based on the arg
arugment.有一种方法基于
arg
返回 object。 The developer has provided a cast, to coerce the object into the MyClass
type.开发人员提供了一个强制转换,将 object 强制转换为
MyClass
类型。
This is common in a Singleton pattern (where the same object instance is returned if the arg
argument is the same), or in a static constructor.这在 Singleton 模式(如果
arg
参数相同,则返回相同的 object 实例)或 static 构造函数中很常见。 Usually the method is doing a new MySubclass(... )
somewhere and returning that.通常该方法在某处执行
new MySubclass(... )
并返回它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.