Guava 介绍

来源:互联网 发布:超级淘宝店txt下载 编辑:程序博客网 时间:2024/06/03 20:42

Guava 介绍

Guava是gooogle开放的Java开源库,提高了最佳代码实践并减少代码错误。内置了很多适用的集合方法,缓存机制,原始类型工具,并发编程,通用注解,字符串处理,I/O以及验证等功能。
本文通过简单直接的示例来引入Guava包,希望引起兴趣。

缓存

缓存在软件设计中经常用到,这里看看guava提供的缓存功能。LoadingCache接口声明如下:

   @Beta   @GwtCompatible   public interface LoadingCache<K,V> extends Cache<K,V>, Function<K,V>

接口中提供了一些便捷的方法用于操作缓存。这里直接通过示例来说明:

一个实体类,需要缓存:

class Employee {   String name;   String dept;   String emplD;   public Employee(String name, String dept, String empID) {      this.name = name;      this.dept = dept;      this.emplD = empID;   }   public String getName() {      return name;   }   public void setName(String name) {      this.name = name;   }   public String getDept() {      return dept;   }   public void setDept(String dept) {      this.dept = dept;   }   public String getEmplD() {      return emplD;   }   public void setEmplD(String emplD) {      this.emplD = emplD;   }   @Override   public String toString() {      return MoreObjects.toStringHelper(Employee.class)      .add("Name", name)      .add("Department", dept)      .add("Emp Id", emplD).toString();   }    }

实现缓存的应用代码:

public class CacheTester {   public static void main(String args[]) {      //create a cache for employees based on their employee id      LoadingCache<String, Employee> employeeCache =          CacheBuilder.newBuilder()            .maximumSize(100) // maximum 100 records can be cached            .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access            .build(new CacheLoader<String, Employee>(){ // build the cacheloader               @Override               public Employee load(String empId) throws Exception {                  //make the expensive call                  return getFromDatabase(empId);               }             });      try {                  //on first invocation, cache will be populated with corresponding         //employee record         System.out.println("Invocation #1");         System.out.println(employeeCache.get("100"));         System.out.println(employeeCache.get("103"));         System.out.println(employeeCache.get("110"));         //second invocation, data will be returned from cache         System.out.println("Invocation #2");         System.out.println(employeeCache.get("100"));         System.out.println(employeeCache.get("103"));         System.out.println(employeeCache.get("110"));      }catch (ExecutionException e) {         e.printStackTrace();      }   }   private static Employee getFromDatabase(String empId) {      Employee e1 = new Employee("Mahesh", "Finance", "100");      Employee e2 = new Employee("Rohan", "IT", "103");      Employee e3 = new Employee("Sohan", "Admin", "110");      Map<String, Employee> database = new HashMap<String, Employee>();      database.put("100", e1);      database.put("103", e2);      database.put("110", e3);      System.out.println("Database hit for" + empId);      return database.get(empId);          }}

字符串工具类

Guava提供了很多高级字符串工具类,这里介绍下字符串格式转换:

首先介绍下其定义的几中枚举常量:

  • LOWER_CAMEL
    小写字母开头的骆驼命名方式变量,如: “lowerCamel”.

  • LOWER_HYPHEN
    小写字母有连字符连接方式变量,如:”lower-hyphen”.

  • LOWER_UNDERSCORE
    小写字母有下划线连接方式变量,如:”lower_underscore”.

  • UPPER_CAMEL
    大写字母开头的下划线方式变量,如: “UpperCamel”.

  • UPPER_UNDERSCORE
    大写字母有下划线连接方式变量,如:”UPPER_UNDERSCORE”.

下面示例其转换功能,在自己实现生成代码功能经常用到,如数据库命名为下划线方式,对应java类则是骆驼命名方式。

package com.dataz;import static org.junit.Assert.assertEquals;import org.junit.Test;import com.google.common.base.CaseFormat;/** * 把指定字符串从一种格式转换为另一种格式 * @author Administrator * */public class StringConvertDemoTest {    @Test    public void test1() {        String data = "test-data";        assertEquals("testData", CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, data));    }    @Test    public void test2() {        String data = "test_data";        assertEquals("testData", CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, data));    }    @Test    public void test3() {        String data = "test_data";        assertEquals("TestData", CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, data));    }   }
原创粉丝点击