Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

java - Issue about casting object brackets

I have noticed that there are two ways to cast objects (the difference is the placement of the outer parenthesis):

 1. SimpleType simpleType = ((SimpleType) (property.getType()));
 2. SimpleType simpleType = ((SimpleType) property).getType();

Are they doing the same thing ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are they doing the same thing ?

No they are not.

  • The first one is casting your value returned from property.getType() to SimpleType. (Invocation is done before Casting)
  • The second one is first casting your property to SimpleType and then invoking the getType() method on it. (Casting is done before Invocation).

You can also understand it from the precedence of parenthesis. Since it has the highest precedence, it will be evaluated first.

First Case: -

So, in ((SimpleType) (property.getType()));: -

(property.getType())

is evaluated first, then the casting is performed. In fact you don't really need a parenthesis around that. (property binds tighter to the dot (.) operator than the cast operator). So, invocation will always be done before casting. Unless you force it to reverse as in the below case: -

Second Case : -

In ((SimpleType) property).getType(): -

((SimpleType) property)

is evaluated first, then the invocation is done. As, now you have enclosed property inside the brackets, due to which it binds tighter to the cast operator, due to higher precedence enforced by parenthesis.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...