首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

import static简单化代码

2012-10-09 
import static简化代码喜欢定义常量的哥们你伤不起啊,好处当然是大大滴,但是定义的名字太长会影响到代码本

import static简化代码

喜欢定义常量的哥们你伤不起啊,好处当然是大大滴,但是定义的名字太长会影响到代码本身的美观程度

?

一般定义常量,会先写一个类专门放置,例如:

?

?

package com.opencfg.gateway.server.constant;public final class GateWayServerConstant {public static final String PARAM_NAME_LOCAL_CLUSTER_DEFAULT_IP = "0.0.0.0";public static final String PARAM_NAME_LOCAL_CLUSTER_DEFAULT_PORT = "36800";public static final int GET_THREAD_POOL_SIZE() {return Runtime.getRuntime().availableProcessors();}}
?

?

?

?

使用这些常量,通常是这样做的:

?

import com.opencfg.gateway.server.constant.GateWayServerConstant;public class GateWayServer {public static void init () {log("Local IP is " + GateWayServerConstant.PARAM_NAME_LOCAL_CLUSTER_DEFAULT_IP);log("Local Port is " + GateWayServerConstant.PARAM_NAME_LOCAL_CLUSTER_DEFAULT_PORT);log("Thread Pool size is " + GateWayServerConstant.GET_THREAD_POOL_SIZE());}}
?

?

?

这样虽然达到了常量统一定义的效果,但是一点也不美观,代码稍长就会换行,影响代码阅读,为了使我们写的代码更具有

?

阅读性,我们可以import?static :

?

import static com.opencfg.gateway.server.constant.GateWayServerConstant.*;public class GateWayServer {public static void init () {log("Local IP is " + PARAM_NAME_LOCAL_CLUSTER_DEFAULT_IP);log("Local Port is " + PARAM_NAME_LOCAL_CLUSTER_DEFAULT_PORT);log("Thread Pool size is " + GET_THREAD_POOL_SIZE());}}
?

?

这里import static 最后.*,是把GateWayServerConstant类的所方法与便利都导入到当前类中,

?

如果只是用其中的几个,也可以单独导入.

?

这个是JDK1.5给我们带来的特性,如果使用这个特性,请首先保证你的JDK版本大于1.5.

?

这个特性对于常量哥简化代码来说,比较有效果 :)

热点排行