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.

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值