java - 在 JAVA 中是否有类似 ActionScript 3's "with"keyword 的东西?

标签 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; 
    } 
}

最佳答案

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。这允许将另一个 classstatic 成员导入到当前 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));
}

您可以看到,这使代码的可读性有所降低。 outmaxPI 的来源并不是特别明显。

关于java - 在 JAVA 中是否有类似 ActionScript 3's "with"keyword 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091362/

相关文章:

java - 如何在不使用 JOIN 的情况下为 JPQL 中的 Collection 子句执行参数绑定(bind)?

c# - java.util 在 vi​​sual studio 2010 中不起作用

java - 在桌面应用程序中处理 Java 最大内存的适当策略是什么?

actionscript-3 - 在使用 Actionscript 和 MXML 编写的 Flex 程序中调试内存泄漏的最佳方法是什么?

javascript - AS3 : Reading the DOM

java - FileLocator 的 toFileURL 方法忽略空文件夹

flash - 静态函数中的动态变量名

php - 实现关键字比较方案(反向搜索)

Meteor:可以从我的数据库中搜索 google 蜘蛛词吗?

c# - 使用 Scintilla 添加关键字