3

In switching from AS3 to JAVA I am finding there are a few minor niceties that I miss, one of them specifically being the with keyword. Is there anything similar to this in JAVA (6 or less)?

I am parsing values out of an object and would rather write something like:

/** 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; 
    } 
}
4

1 回答 1

2

with该语句似乎有两个用例。

this1)在特定上下文中更改 的值

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)从另一个导入方法,class以便它们可以不合格地使用。

public static void main(String[] args) throws Exception {
    System.out.println(Math.max(Math.PI, 3));
}

可以更改,在 java 中使用import static. 这允许static将另一个成员class导入到当前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

于 2013-08-06T22:18:59.420 回答