展会信息港展会大全

在Eclipse中导入static元素
来源:互联网   发布日期:2016-01-14 14:42:28   浏览:2523次  

导读: 你知道在 Eclipse中怎么快速导入Static变量、方法吗?说实话,以前我也不知道。但是今天我知道了“Ctrl+Shift+M” (Source>Add Import)快捷键不...

你知道在

Eclipse中怎么快速导入Static变量、方法吗?说实话,以前我也不知道。但是今天我知道了“Ctrl+Shift+M” (Source>Add Import)快捷键不仅可以增加缺失的导入,还可以用来在Java程序中导入静态方法和变量。假设你正在从一个工具类,比如TimeUnit,通过类名使用很多静态变量,也就是我们引用静态变量。在Eclipse IDE中,你可以将引用变量完全选中并按下“Ctrl+Shift+M”快捷键,它会使用Java中的静态导入来自动导入静态元素。

例如,如果你的类中有以下代码,像第一张和第二章截图展示的那样。可以选中TimeUnit.SECONDS,接着按下快捷键“Ctrl+Shift+M”来在代码中静态引入SECONDS变量。

import java.util.concurrent.TimeUnit;

/**

* Java Program to show how you can static import some class variables.

*

* @author WINDOWS 8

*/

public class Test {

public static void main(String args[]){

System.out.println(TimeUnit.SECONDS);

System.out.println(TimeUnit.MINUTES);

System.out.println(TimeUnit.DAYS);

}

}

像上面展示的那样,仅需要标记或选中TimeUnit.SECONDS,然后敲下“type Ctrl+Shift+M”快捷键或者选择“Menu”选项中“Add import”来从java.util.TimeUnit类中引入静态变量。在这段代码中重复三次,可以将上面的代码简化为如下的代码,如第四张截图显示的那样:

import static java.util.concurrent.TimeUnit.DAYS;

import static java.util.concurrent.TimeUnit.MINUTES;

import static java.util.concurrent.TimeUnit.SECONDS;

import java.util.concurrent.TimeUnit;

/**

* Sample program to demonstrate Eclipse shortcut for doing static import.

*

* @author WINDOWS 8

*/

public class Test {

public static void main(String args[]){

System.out.println(SECONDS);

System.out.println(MINUTES);

System.out.println(DAYS);

}

}

顺便说一下,这个特性并不是没有漏洞的。例如,如果你没有提前导入java.util.concurrent.TimeUnit这个类,那么 TimeUnit class就会缺失。这样的情况下, “Ctrl+Shift+M”快捷键是没有效果的。只有在代码中导入相应类后,你需要选择相应成员,然后按下“ Ctrl+Shift+M”来引入静态字段或方法。一次敲击不能导入所有静态成员,你需要首先选择每一个这类元素,然后有多少个静态成员,就按多少次快捷 键。

原文链接:

javarevisited 翻译:

ImportNew.com-

Calarence

译文链接:

http://www.importnew.com/14074.html

赞助本站

人工智能实验室

相关热词: eclipse 编程 软件开发

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港