在从 AS3 切换到 JAVA 的过程中,我发现我错过了一些小细节,其中之一就是 with关键词。
JAVA(6以下)有类似的东西吗?
我正在从一个对象中解析出值,我宁愿这样写:
/** Example in AS3 **/
function FancyParsingContructorInAS3(values:Object):void {
with (values) {
this.x = x; // functionally equivalent to `this.x = values.x;`
this.y = y;
this.width = width;
this.height = height;
}
}
with
语句似乎有两个用例。
1) 在特定上下文中更改this
的值
public class App {
public void stuff() {
//this refers to the current instance of App
final Object obj = new Object();
with(obj) {
//this refers to obj
}
}
}
Java 中没有这样的东西。您只需将方法代码放入 Object
即可。
2) 从另一个类
导入方法,以便它们可以无限制地使用。
public static void main(String[] args) throws Exception {
System.out.println(Math.max(Math.PI, 3));
}
可以更改,在 java 中使用 import static
。这允许将另一个 class
的 static
成员导入到当前 class
中。添加以下三个导入语句:
import static java.lang.System.out;
import static java.lang.Math.max;
import static java.lang.Math.PI;
将允许您改写
public static void main(String[] args) throws Exception {
out.println(max(PI, 3));
}
您可以看到,这使代码的可读性有所降低。 out
、max
和 PI
的来源并不是特别明显。