在没有括号的Java中调用新对象的方法:操作违规的顺序? [英] Calling a method on a new object in Java without parentheses: order of operations violation?

查看:136
本文介绍了在没有括号的Java中调用新对象的方法:操作违规的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此Java运算符优先级和关联性表,成员访问优先级高于 new 运算符。

According to this table of Java operator precedence and associativity, member access has higher precedence than the new operator.

但是,给定一个类 myClass 和一个非静态成员函数 myFunction ,以下代码行有效:

However, given a class myClass and a non-static member function myFunction, the following line of code is valid:

new myClass()。myFunction();

如果之前已经过评估 new ,该行怎么执行?换句话说,为什么不需要括号?

If . is evaluated before new, how can this line be executed? In other words, why aren't parentheses required?

(new myClass())。myFunction();

我的猜测是因为()共享优先权。,首先评估 myClass(),因此编译器甚至在评估 new 关键字之前就知道了 myClass 正在调用零参数的构造函数。但是,这似乎仍然暗示第一行应该与 new(myClass()。myFunction()); 相同,不是案例。

My guess is that since () shares precedence with ., the myClass() is evaluated first, and so the compiler knows even before evaluating the new keyword that the myClass constructor with zero parameters is being called. However, this still seems to imply that the first line should be identical to new (myClass().myFunction());, which is not the case.

推荐答案

这是因为语法。运算符的优先级恰好在相同的词汇序列可以用两种不同的方式解析时发挥作用但事实并非如此。

This is because of how the grammar of Java language is defined. Precedence of operators comes into play just when the same lexical sequence could be parsed in two different ways but this is not the case.

为什么?

因为分配定义如下:

Primary: 
  ...
  new Creator

方法调用定义如下:

Selector:
  . Identifier [Arguments]
  ...

并且都在这里使用:

Expression3: 
  ...
  Primary { Selector } { PostfixOp }

所以会发生的是

new myClass().myFunction();

被解析为

         Expression
             |
             |
    ---------+--------
    |                |
    |                |
  Primary        Selector
    |                |
    |                |
 ---+---            ...
 |     |
new   Creator 

所以根据优先级没有选择,因为之前减少了。请注意,对于特殊情况,例如

So there is no choice according to priority because the Primary is reduced before. Mind that for the special situation like

new OuterClass.InnerClass()

类名实际上是在 new 运算符之前解析的,并且确实有处理该情况的规则。如果你想看到它们,请检查语法。

the class name is actually parsed before the new operator and there are rules to handle that case indeed. Check the grammar if you like to see them.

这篇关于在没有括号的Java中调用新对象的方法:操作违规的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆