在JAVA中是否有类似ActionScript 3的“with”关键字?

时间:2013-08-06 22:06:44

标签: java actionscript-3 keyword

在从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; 
    } 
}

1 个答案:

答案 0 :(得分:2)

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

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

可以在import static的java中更改。这样,其他static的{​​{1}}成员就可以导入当前class。添加以下三个import语句:

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)); } outmax的来源并不是特别明显。

相关问题