`
BucketLi
  • 浏览: 189799 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
博客专栏
5a76a659-f8e6-3bf3-b39a-8ae8f7a0f9d9
Percolator与分布...
浏览量:5547
社区版块
存档分类
最新评论

java代码细节

 
阅读更多
看代码过程中一些细节记录,不断补充。质量可靠,开发高效的捷径在于使用一些成熟的库和代码,并且了解其特性和主要原理,特别是工具类。

1.向左补充特定字符
StringUtils.leftPad(String.valueOf(i), startStr.length(), '0')


2.值为null抛IllegalArgumentException
Assert.notNull(mode);


3.截取特定字符之前的字符串
StringUtils.substringBefore(rawValue, "[")


4.匹配任意一个字符
StringUtils.containsAny(value, new char[] { '*', '?', '+', '|', '(', ')', '{', '}', '[', ']', '\\', '$','^', '.' })


5.将一个类转换成一个特定格式的string
ToStringBuilder.reflectionToString(this);


6.反射设置值之前让字段可访问
ReflectionUtils.makeAccessible(field);


7.拷贝同一个类的对象之间字段
BeanUtils.copyProperties(this, globalParmeter);


8.对collection进行排序
Collections.sort(processIds);


9.fastJson转换json String到特定对象
JSON.parseObject(json, targetClass);


10.使用String format字符串
private static final String PATH        = "/destinations/%s";
private static final String CURSOR_PATH = PATH + "/%s/cursor"
String path = String.format(CURSOR_PATH, destination, String.valueOf(clientId));


11.使用apache commons 包的RandomUtil进行随机数选择
this.index = RandomUtils.nextInt(this.managerAddress.size());


12.按某个分隔符拼接字符串列表
String addr = StringUtils.join(node.getParameters().getZkCluster().getServerList(), ',');


13.获取Collection中最小值
Collections.min(progress.keySet())


14.拷贝两个对象之间的同名属性,不需要对象类型一致
BeanUtils.copyProperties(authenticationInfo, datasourceInfo);


15.有时候使用系统启动时设置的系统变量也能达到不错的效果
String nid = System.getProperty(NID_NAME);


16.单点到单点(可能有HA)的面向对象编程可以使用rmi来(比如spring)做通讯
   
    RmiServiceExporter export = new RmiServiceExporter();
        export.setServiceName("endpoint");
        export.setService(this);// 暴露自己
        export.setServiceInterface(CommunicationEndpoint.class);
        export.setRegistryHost(host);
        export.setRegistryPort(port);
        export.setAlwaysCreateRegistry(alwaysCreateRegistry);/


17.有时候可以内嵌jetty容器(org.eclipse.jetty)来构建web应用,特别是快速测试阶段,具备动态代码更新的能力
       
<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-webapp</artifactId>
		</dependency>

   
public void start() throws Exception {
        Resource configXml = Resource.newSystemResource("jetty.xml");
        XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
        server = (Server) configuration.configure();

        Handler handler = server.getHandler();
        if (handler != null && handler instanceof WebAppContext) {
            WebAppContext webAppContext = (WebAppContext) handler;
            webAppContext.setResourceBase(JettyEmbedServer.class.getResource("/webapp").toString());
        }
        server.start();
        if (logger.isInfoEnabled()) {
            logger.info("##Jetty Embed Server is startup!");
        }
    }


18.使用spring的时候不一定使用init-method方式初始化bean,也可以实现InitializingBean接口实现afterPropertiesSet()的方式初始化。

19. 添加shutdownhook在程序关闭的时候做一些操作
Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    
                }
            });


20.得到异常的整个堆栈
 ExceptionUtils.getFullStackTrace(e));


21.得到内存使用率
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();


22.大量产生String的时候,并且有很大概率相同的时候,可以用intern优化
sql.toString().intern();// intern优化,避免出现大量相同的字符串


23.不可变map
Collections.unmodifiableMap(parameters);


24.根据host获取ip
InetAddress.getByName(hostName).getHostAddress();


25.获取原始类型数据,valueOf是多了一个装箱操作
Double.parseDouble(xx);


26.直接读取文件内容为string的便利方法
String json = FileUtils.readFileToString(dataFile, charset.name());


27.多行join成一行
String ruleStr = StringUtils.join(IOUtils.readLines(resource.getInputStream()), SystemUtils.LINE_SEPARATOR);


28.可以使用apache的Configuration来load各种配置,其有很多便利功能
PropertiesConfiguration config = new PropertiesConfiguration();
config.load(new FileInputStream(conf));


29.使用apache的StringUtils截取字符串
StringUtils.substringAfter(conf, CLASSPATH_URL_PREFIX);


30.google guava包中的一些有用的细节
this.queries = ImmutableList.copyOf(checkNotNull(queries, "queries is null"));

HostAndPort host = HostAndPort.fromString(server);

Splitter NAME_VALUE_SPLITTER = Splitter.on('=').limit(2).trimResults();

MapSplitter TAGS_SPLITTER=Splitter.on("\n").trimResults().withKeyValueSeparator('=')

checkArgument(name.indexOf('=') < 0, "Session property name must not contain '=': %s", name);

ImmutableList.builder()
                .add("suite")
                .add("query")
                .addAll(tagNames)
                .add("wallTimeP50")
                .add("wallTimeMean")
                .add("wallTimeStd")
                .add("processCpuTimeP50")
                .add("processCpuTimeMean")
                .add("processCpuTimeStd")
                .add("queryCpuTimeP50")
                .add("queryCpuTimeMean")
                .add("queryCpuTimeStd")
                .add("status")
                .add("error")
                .build()

Joiner.on('\t').join(values);//value是list

MoreObjects.toStringHelper(this)
                .add("name", name)
                .add("tags", tags)
                .toString();

Map<Type, String> SQL_TYPES = ImmutableMap.<Type, String>builder()
            .put(BOOLEAN, "boolean")
            .put(BIGINT, "bigint")
            .put(DOUBLE, "double precision")
            .put(VARCHAR, "varchar")
            .put(VARBINARY, "varbinary")
            .put(DATE, "date")
            .put(TIME, "time")
            .put(TIME_WITH_TIME_ZONE, "time with timezone")
            .put(TIMESTAMP, "timestamp")
            .put(TIMESTAMP_WITH_TIME_ZONE, "timestamp with timezone")
            .build();

int jitter = ThreadLocalRandom.current().nextInt(100);//jdk自带的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics