在Eclipse中导入static元素

开发 后端
Eclipse中怎么快速导入Static变量、方法吗?说实话,以前我也不知道。但是今天我知道了“Ctrl+Shift+M” (Source>Add Import)快捷键不仅可以增加缺失的导入,还可以用来在Java程序中导入静态方法和变量。

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

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

  1. import java.util.concurrent.TimeUnit; 
  2.   
  3. /** 
  4.  * Java Program to show how you can static import some class variables. 
  5.  *  
  6.  * @author WINDOWS 8 
  7.  */ 
  8.   
  9. public class Test {    
  10.   
  11.     public static void main(String args[]){ 
  12.   
  13.         System.out.println(TimeUnit.SECONDS);  
  14.         System.out.println(TimeUnit.MINUTES); 
  15.         System.out.println(TimeUnit.DAYS); 
  16.   
  17.     } 
  18.   

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

  1. import static java.util.concurrent.TimeUnit.DAYS; 
  2. import static java.util.concurrent.TimeUnit.MINUTES; 
  3. import static java.util.concurrent.TimeUnit.SECONDS; 
  4.   
  5. import java.util.concurrent.TimeUnit; 
  6.   
  7. /** 
  8.  * Sample program to demonstrate Eclipse shortcut for doing static import. 
  9.  *  
  10.  * @author WINDOWS 8 
  11.  */ 
  12.   
  13. public class Test {    
  14.   
  15.     public static void main(String args[]){ 
  16.   
  17.         System.out.println(SECONDS); 
  18.         System.out.println(MINUTES); 
  19.         System.out.println(DAYS); 
  20.   
  21.     } 
  22.   

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

原文链接: javarevisited 翻译: ImportNew.com Calarence
译文链接: http://www.importnew.com/14074.html

责任编辑:张伟 来源: ImportNew
相关推荐

2009-06-29 16:19:57

JSP Servlet

2010-04-27 13:31:31

2018-08-10 09:22:20

Windows 10Windows照片

2009-08-18 09:07:02

Windows 7身份凭证

2022-05-05 09:45:16

KVM虚拟机磁盘

2017-02-08 14:30:08

Chrome密码浏览器

2024-03-08 08:51:59

Gomain函数

2010-03-18 16:51:00

python语法入门

2015-01-15 10:33:22

Android Stu导入开源库

2020-05-22 13:40:09

Linux文件系统

2021-02-20 18:00:26

rangerLinux

2020-05-25 09:09:01

Linux件系统导航

2024-03-12 09:13:28

Go语言main

2011-09-13 17:52:37

Eclipse And

2009-06-02 15:20:16

eclipse tomtomcatplugitomcatplugi

2009-06-17 17:44:41

Eclipse插件Sp

2013-04-25 10:03:07

unity3D手机游戏引擎

2009-06-05 14:59:31

Eclipse中配置T

2011-07-14 08:56:34

Sql Server

2017-04-24 20:30:47

数据库工具导入数据
点赞
收藏

51CTO技术栈公众号