hutool-core,lang-1

lang-1

public class AnsiEncoderTest {
  @Test
  public void encodeTest(){
    final String encode = AnsiEncoder.encode(AnsiColor.GREEN, "Hutool test");
    Assert.assertEquals("\u001B[32mHutool test\u001B[0;39m", encode);
  }
  @Test
  @Ignore
  public void colorfulEncodeTest(){
    String text = "Hutool▀████▀";
    final AnsiColors ansiColors = new AnsiColors(AnsiColors.BitDepth.EIGHT);
    Color[] colorArray = new Color[]{
        Color.BLACK,      Color.BLUE,
        Color.CYAN,       Color.DARK_GRAY,
        Color.GRAY,       Color.GREEN,
        Color.LIGHT_GRAY,   Color.MAGENTA,
        Color.ORANGE,     Color.PINK,
        Color.RED,        Color.WHITE,
        Color.YELLOW
    };
    for (int i = 0; i < colorArray.length; i++) {
      Color foreColor = colorArray[i];
      AnsiElement foreElement = ansiColors.findClosest(foreColor).toAnsiElement(ForeOrBack.FORE);
      Color backColor = new Color(255 - foreColor.getRed(), 255 - foreColor.getGreen(), 255 - foreColor.getBlue());
      AnsiElement backElement = ansiColors.findClosest(backColor).toAnsiElement(ForeOrBack.BACK);
      String encode = AnsiEncoder.encode(foreElement, backElement, text);
      Console.print( i%2==1?encode+"\n":encode);
    }
  }
  @Test
  public void colorMappingTest(){
    String text4 = "RGB:({},{},{})--4bit ";
    String text8 = "RGB:({},{},{})--8bit ";
    final AnsiColors ansiColors4Bit = new AnsiColors(AnsiColors.BitDepth.FOUR);
    final AnsiColors ansiColors8Bit = new AnsiColors(AnsiColors.BitDepth.EIGHT);
    int count = 0;
    int from = 100000;
    int until = 120000;
    for (int r = 0; r < 256; r++) {
      if (count>until)break;
      for (int g = 0; g < 256; g++) {
        if (count>until)break;
        for (int b = 0; b < 256; b++) {
          count++;
          if (count<from)continue;
          if (count>until)break;
          AnsiElement backElement4bit = ansiColors4Bit.findClosest(new Color(r,g,b)).toAnsiElement(ForeOrBack.BACK);
          AnsiElement backElement8bit = ansiColors8Bit.findClosest(new Color(r,g,b)).toAnsiElement(ForeOrBack.BACK);
          String encode4 = AnsiEncoder.encode( backElement4bit,text4);
          String encode8 = AnsiEncoder.encode( backElement8bit,text8);
          //Console.log(StrUtil.format(encode4,r,g,b)+StrUtil.format(encode8,r,g,b));
        }
      }
    }
  }
}
public class CallerTest {
  
  @Test
  public void getCallerTest() {
    Class<?> caller = CallerUtil.getCaller();
    Assert.assertEquals(this.getClass(), caller);
    
    Class<?> caller0 = CallerUtil.getCaller(0);
    Assert.assertEquals(CallerUtil.class, caller0);
    
    Class<?> caller1 = CallerUtil.getCaller(1);
    Assert.assertEquals(this.getClass(), caller1);
  }
  
  @Test
  public void getCallerCallerTest() {
    Class<?> callerCaller = CallerTestClass.getCaller();
    Assert.assertEquals(this.getClass(), callerCaller);
  }
  
  private static class CallerTestClass{
    public static Class<?> getCaller(){
      return CallerUtil.getCallerCaller();
    }
  }
}
public class CallerUtilTest {
  @Test
  public void getCallerMethodNameTest() {
    final String callerMethodName = CallerUtil.getCallerMethodName(false);
    Assert.assertEquals("getCallerMethodNameTest", callerMethodName);
    final String fullCallerMethodName = CallerUtil.getCallerMethodName(true);
    Assert.assertEquals("cn.hutool.core.lang.caller.CallerUtilTest.getCallerMethodNameTest", fullCallerMethodName);
  }
}
public class LambdaUtilTest {
  @Test
  public void getMethodNameTest() {
    final String methodName = LambdaUtil.getMethodName(MyTeacher::getAge);
    Assert.assertEquals("getAge", methodName);
  }
  @Test
  public void getFieldNameTest() {
    final String fieldName = LambdaUtil.getFieldName(MyTeacher::getAge);
    Assert.assertEquals("age", fieldName);
  }
  @Test
  public void resolveTest() {
    // 引用构造函数
    Assert.assertEquals(MethodHandleInfo.REF_newInvokeSpecial,
        LambdaUtil.resolve(MyTeacher::new).getImplMethodKind());
    // 数组构造函数引用
    Assert.assertEquals(MethodHandleInfo.REF_invokeStatic,
        LambdaUtil.resolve(MyTeacher[]::new).getImplMethodKind());
    // 引用静态方法
    Assert.assertEquals(MethodHandleInfo.REF_invokeStatic,
        LambdaUtil.resolve(MyTeacher::takeAge).getImplMethodKind());
    // 引用特定对象的实例方法
    Assert.assertEquals(MethodHandleInfo.REF_invokeVirtual,
        LambdaUtil.resolve(new MyTeacher()::getAge).getImplMethodKind());
    // 引用特定类型的任意对象的实例方法
    Assert.assertEquals(MethodHandleInfo.REF_invokeVirtual,
        LambdaUtil.resolve(MyTeacher::getAge).getImplMethodKind());
  }
  @Test
  public void getRealClassTest() {
    // 引用特定类型的任意对象的实例方法
    final Class<MyTeacher> functionClass = LambdaUtil.getRealClass(MyTeacher::getAge);
    Assert.assertEquals(MyTeacher.class, functionClass);
    // 枚举测试,不会导致类型擦除
    final Class<LambdaKindEnum> enumFunctionClass = LambdaUtil.getRealClass(LambdaKindEnum::ordinal);
    Assert.assertEquals(LambdaKindEnum.class, enumFunctionClass);
    // 调用父类方法,能获取到正确的子类类型
    final Class<MyTeacher> superFunctionClass = LambdaUtil.getRealClass(MyTeacher::getId);
    Assert.assertEquals(MyTeacher.class, superFunctionClass);
    final MyTeacher myTeacher = new MyTeacher();
    // 引用特定对象的实例方法
    final Class<MyTeacher> supplierClass = LambdaUtil.getRealClass(myTeacher::getAge);
    Assert.assertEquals(MyTeacher.class, supplierClass);
    // 枚举测试,只能获取到枚举类型
    final Class<Enum<?>> enumSupplierClass = LambdaUtil.getRealClass(LambdaKindEnum.REF_NONE::ordinal);
    Assert.assertEquals(Enum.class, enumSupplierClass);
    // 调用父类方法,只能获取到父类类型
    final Class<Entity<?>> superSupplierClass = LambdaUtil.getRealClass(myTeacher::getId);
    Assert.assertEquals(Entity.class, superSupplierClass);
    // 引用静态带参方法,能够获取到正确的参数类型
    final Class<MyTeacher> staticFunctionClass = LambdaUtil.getRealClass(MyTeacher::takeAgeBy);
    Assert.assertEquals(MyTeacher.class, staticFunctionClass);
    // 引用父类静态带参方法,只能获取到父类类型
    final Class<Entity<?>> staticSuperFunctionClass = LambdaUtil.getRealClass(MyTeacher::takeId);
    Assert.assertEquals(Entity.class, staticSuperFunctionClass);
    // 引用静态无参方法,能够获取到正确的类型
    final Class<MyTeacher> staticSupplierClass = LambdaUtil.getRealClass(MyTeacher::takeAge);
    Assert.assertEquals(MyTeacher.class, staticSupplierClass);
    // 引用父类静态无参方法,能够获取到正确的参数类型
    final Class<MyTeacher> staticSuperSupplierClass = LambdaUtil.getRealClass(MyTeacher::takeIdBy);
    Assert.assertEquals(MyTeacher.class, staticSuperSupplierClass);
  }
  @Data
  @AllArgsConstructor
  static class MyStudent {
    private String name;
  }
  @Data
  public static class Entity<T> {
    private T id;
    public static <T> T takeId() {
      return new Entity<T>().getId();
    }
    public static <T> T takeIdBy(final Entity<T> entity) {
      return entity.getId();
    }
  }
  @Data
  @EqualsAndHashCode(callSuper = true)
  static class MyTeacher extends Entity<MyTeacher> {
    public static String takeAge() {
      return new MyTeacher().getAge();
    }
    public static String takeAgeBy(final MyTeacher myTeacher) {
      return myTeacher.getAge();
    }
    public String age;
  }
  /**
   * 测试Lambda类型枚举
   */
  enum LambdaKindEnum {
    REF_NONE,
    REF_getField,
    REF_getStatic,
    REF_putField,
    REF_putStatic,
    REF_invokeVirtual,
    REF_invokeStatic,
    REF_invokeSpecial,
    REF_newInvokeSpecial,
  }
  @Test
  public void lambdaClassNameTest() {
    final String lambdaClassName1 = LambdaUtilTestHelper.getLambdaClassName(MyTeacher::getAge);
    final String lambdaClassName2 = LambdaUtilTestHelper.getLambdaClassName(MyTeacher::getAge);
    Assert.assertNotEquals(lambdaClassName1, lambdaClassName2);
  }
  static class LambdaUtilTestHelper {
    public static <P> String getLambdaClassName(final Func1<P, ?> func) {
      return func.getClass().getName();
    }
  }
}
public class CityHashTest {
  @Test
  public void hash32Test() {
    int hv = CityHash.hash32(StrUtil.utf8Bytes("你"));
    Assert.assertEquals(1290029860, hv);
    hv = CityHash.hash32(StrUtil.utf8Bytes("你好"));
    Assert.assertEquals(1374181357, hv);
    hv = CityHash.hash32(StrUtil.utf8Bytes("见到你很高兴"));
    Assert.assertEquals(1475516842, hv);
    hv = CityHash.hash32(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
    Assert.assertEquals(0x51020cae, hv);
  }
  @Test
  public void hash64Test() {
    long hv = CityHash.hash64(StrUtil.utf8Bytes("你"));
    Assert.assertEquals(-4296898700418225525L, hv);
    hv = CityHash.hash64(StrUtil.utf8Bytes("你好"));
    Assert.assertEquals(-4294276205456761303L, hv);
    hv = CityHash.hash64(StrUtil.utf8Bytes("见到你很高兴"));
    Assert.assertEquals(272351505337503793L, hv);
    hv = CityHash.hash64(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
    Assert.assertEquals(-8234735310919228703L, hv);
  }
}
public class MetroHashTest {
  @Test
  public void testEmpty() {
    Assert.assertEquals("31290877cceaea29", HexUtil.toHex(MetroHash.hash64(StrUtil.utf8Bytes(""), 0)));
  }
  @Test
  public void metroHash64Test() {
    byte[] str = "我是一段测试123".getBytes(CharsetUtil.CHARSET_UTF_8);
    final long hash64 = MetroHash.hash64(str);
    Assert.assertEquals(62920234463891865L, hash64);
  }
  @Test
  public void metroHash128Test() {
    byte[] str = "我是一段测试123".getBytes(CharsetUtil.CHARSET_UTF_8);
    final long[] hash128 = MetroHash.hash128(str).getLongArray();
    Assert.assertEquals(4956592424592439349L, hash128[0]);
    Assert.assertEquals(6301214698325086246L, hash128[1]);
  }
  /**
   * 数据量越大 MetroHash 优势越明显,
   */
  @Test
  @Ignore
  public void bulkHashing64Test() {
    String[] strArray = getRandomStringArray();
    long startCity = System.currentTimeMillis();
    for (String s : strArray) {
      CityHash.hash64(s.getBytes());
    }
    long endCity = System.currentTimeMillis();
    long startMetro = System.currentTimeMillis();
    for (String s : strArray) {
      MetroHash.hash64(StrUtil.utf8Bytes(s));
    }
    long endMetro = System.currentTimeMillis();
    System.out.println("metroHash =============" + (endMetro - startMetro));
    System.out.println("cityHash =============" + (endCity - startCity));
  }
  /**
   * 数据量越大 MetroHash 优势越明显,
   */
  @Test
  @Ignore
  public void bulkHashing128Test() {
    String[] strArray = getRandomStringArray();
    long startCity = System.currentTimeMillis();
    for (String s : strArray) {
      CityHash.hash128(s.getBytes());
    }
    long endCity = System.currentTimeMillis();
    long startMetro = System.currentTimeMillis();
    for (String s : strArray) {
      MetroHash.hash128(StrUtil.utf8Bytes(s));
    }
    long endMetro = System.currentTimeMillis();
    System.out.println("metroHash =============" + (endMetro - startMetro));
    System.out.println("cityHash =============" + (endCity - startCity));
  }
  private static String[] getRandomStringArray() {
    String[] result = new String[10000000];
    int index = 0;
    while (index < 10000000) {
      result[index++] = RandomUtil.randomString(RandomUtil.randomInt(64));
    }
    return result;
  }
}
public class MurmurHashTest {
  @Test
  public void hash32Test() {
    int hv = MurmurHash.hash32(StrUtil.utf8Bytes("你"));
    Assert.assertEquals(-1898877446, hv);
    hv = MurmurHash.hash32(StrUtil.utf8Bytes("你好"));
    Assert.assertEquals(337357348, hv);
    hv = MurmurHash.hash32(StrUtil.utf8Bytes("见到你很高兴"));
    Assert.assertEquals(1101306141, hv);
    hv = MurmurHash.hash32(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
    Assert.assertEquals(-785444229, hv);
  }
  @Test
  public void hash64Test() {
    long hv = MurmurHash.hash64(StrUtil.utf8Bytes("你"));
    Assert.assertEquals(-1349759534971957051L, hv);
    hv = MurmurHash.hash64(StrUtil.utf8Bytes("你好"));
    Assert.assertEquals(-7563732748897304996L, hv);
    hv = MurmurHash.hash64(StrUtil.utf8Bytes("见到你很高兴"));
    Assert.assertEquals(-766658210119995316L, hv);
    hv = MurmurHash.hash64(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
    Assert.assertEquals(-7469283059271653317L, hv);
  }
}
public class InternUtilTest {
  /**
   * 检查规范字符串是否相同
   */
  @SuppressWarnings("StringOperationCanBeSimplified")
  @Test
  public void weakTest(){
    final Interner<String> interner = InternUtil.createWeakInterner();
    String a1 = RandomUtil.randomString(RandomUtil.randomInt(100));
    String a2 = new String(a1);
    Assert.assertNotSame(a1, a2);
    Assert.assertSame(interner.intern(a1), interner.intern(a2));
  }
}
public class LazyFunLoaderTest {
  static class BigObject {
    private boolean isDestroy = false;
    public void destroy() {
      this.isDestroy = true;
    }
  }
  @Test
  public void test1() {
    LazyFunLoader<BigObject> loader = new LazyFunLoader<>(BigObject::new);
    Assert.assertNotNull(loader.get());
    Assert.assertTrue(loader.isInitialize());
    // 对于某些对象,在程序关闭时,需要进行销毁操作
    loader.ifInitialized(BigObject::destroy);
    Assert.assertTrue(loader.get().isDestroy);
  }
  @Test
  public void test2() {
    LazyFunLoader<BigObject> loader = new LazyFunLoader<>(BigObject::new);
    // 若从未使用,则可以避免不必要的初始化
    loader.ifInitialized(it -> {
      Assert.fail();
      it.destroy();
    });
    Assert.assertFalse(loader.isInitialize());
  }
  @Test
  public void testOnLoadStaticFactoryMethod1() {
    LazyFunLoader<BigObject> loader = LazyFunLoader.on(BigObject::new);
    Assert.assertNotNull(loader.get());
    Assert.assertTrue(loader.isInitialize());
    // 对于某些对象,在程序关闭时,需要进行销毁操作
    loader.ifInitialized(BigObject::destroy);
    Assert.assertTrue(loader.get().isDestroy);
  }
  @Test
  public void testOnLoadStaticFactoryMethod2() {
    LazyFunLoader<BigObject> loader = LazyFunLoader.on(BigObject::new);
    // 若从未使用,则可以避免不必要的初始化
    loader.ifInitialized(it -> {
      Assert.fail();
      it.destroy();
    });
  }
}
public class ActualTypeMapperPoolTest {
  @Test
  public void getTypeArgumentTest(){
    final Map<Type, Type> typeTypeMap = ActualTypeMapperPool.get(FinalClass.class);
    typeTypeMap.forEach((key, value)->{
      if("A".equals(key.getTypeName())){
        Assert.assertEquals(Character.class, value);
      } else if("B".equals(key.getTypeName())){
        Assert.assertEquals(Boolean.class, value);
      } else if("C".equals(key.getTypeName())){
        Assert.assertEquals(String.class, value);
      } else if("D".equals(key.getTypeName())){
        Assert.assertEquals(Double.class, value);
      } else if("E".equals(key.getTypeName())){
        Assert.assertEquals(Integer.class, value);
      }
    });
  }
  @Test
  public void getTypeArgumentStrKeyTest(){
    final Map<String, Type> typeTypeMap = ActualTypeMapperPool.getStrKeyMap(FinalClass.class);
    typeTypeMap.forEach((key, value)->{
      if("A".equals(key)){
        Assert.assertEquals(Character.class, value);
      } else if("B".equals(key)){
        Assert.assertEquals(Boolean.class, value);
      } else if("C".equals(key)){
        Assert.assertEquals(String.class, value);
      } else if("D".equals(key)){
        Assert.assertEquals(Double.class, value);
      } else if("E".equals(key)){
        Assert.assertEquals(Integer.class, value);
      }
    });
  }
  public interface BaseInterface<A, B, C> {}
  public interface FirstInterface<A, B, D, E> extends BaseInterface<A, B, String> {}
  public interface SecondInterface<A, B, F> extends BaseInterface<A, B, String> {}
  public static class BaseClass<A, D> implements FirstInterface<A, Boolean, D, Integer> {}
  public static class FirstClass extends BaseClass<Character, Double> implements SecondInterface<Character, Boolean, FirstClass> {}
  public static class SecondClass extends FirstClass {}
  public static class FinalClass extends SecondClass {}
}
public class MethodHandleUtilTest {
  @Test
  public void invokeDefaultTest(){
    Duck duck = (Duck) Proxy.newProxyInstance(
        ClassLoaderUtil.getClassLoader(),
        new Class[] { Duck.class },
        MethodHandleUtil::invokeSpecial);
    Assert.assertEquals("Quack", duck.quack());
    // 测试子类执行default方法
    final Method quackMethod = ReflectUtil.getMethod(Duck.class, "quack");
    String quack = MethodHandleUtil.invokeSpecial(new BigDuck(), quackMethod);
    Assert.assertEquals("Quack", quack);
    // 测试反射执行默认方法
    quack = ReflectUtil.invoke(new Duck() {}, quackMethod);
    Assert.assertEquals("Quack", quack);
  }
  @Test
  public void invokeDefaultByReflectTest(){
    Duck duck = (Duck) Proxy.newProxyInstance(
        ClassLoaderUtil.getClassLoader(),
        new Class[] { Duck.class },
        ReflectUtil::invoke);
    Assert.assertEquals("Quack", duck.quack());
  }
  @Test
  public void invokeStaticByProxyTest(){
    Duck duck = (Duck) Proxy.newProxyInstance(
        ClassLoaderUtil.getClassLoader(),
        new Class[] { Duck.class },
        ReflectUtil::invoke);
    Assert.assertEquals("Quack", duck.quack());
  }
  @Test
  public void invokeTest(){
    // 测试执行普通方法
    final int size = MethodHandleUtil.invokeSpecial(new BigDuck(),
        ReflectUtil.getMethod(BigDuck.class, "getSize"));
    Assert.assertEquals(36, size);
  }
  @Test
  public void invokeStaticTest(){
    // 测试执行普通方法
    final String result = MethodHandleUtil.invoke(null,
        ReflectUtil.getMethod(Duck.class, "getDuck", int.class), 78);
    Assert.assertEquals("Duck 78", result);
  }
  @Test
  public void findMethodTest() throws Throwable {
    MethodHandle handle = MethodHandleUtil.findMethod(Duck.class, "quack",
        MethodType.methodType(String.class));
    Assert.assertNotNull(handle);
    // 对象方法自行需要绑定对象或者传入对象参数
    String invoke = (String) handle.invoke(new BigDuck());
    Assert.assertEquals("Quack", invoke);
    // 对象的方法获取
    handle = MethodHandleUtil.findMethod(BigDuck.class, "getSize",
        MethodType.methodType(int.class));
    Assert.assertNotNull(handle);
    int invokeInt = (int) handle.invoke(new BigDuck());
    Assert.assertEquals(36, invokeInt);
  }
  @Test
  public void findStaticMethodTest() throws Throwable {
    final MethodHandle handle = MethodHandleUtil.findMethod(Duck.class, "getDuck",
        MethodType.methodType(String.class, int.class));
    Assert.assertNotNull(handle);
    // static 方法执行不需要绑定或者传入对象,直接传入参数即可
    final String invoke = (String) handle.invoke(12);
    Assert.assertEquals("Duck 12", invoke);
  }
  @Test
  public void findPrivateMethodTest() throws Throwable {
    final MethodHandle handle = MethodHandleUtil.findMethod(BigDuck.class, "getPrivateValue",
        MethodType.methodType(String.class));
    Assert.assertNotNull(handle);
    final String invoke = (String) handle.invoke(new BigDuck());
    Assert.assertEquals("private value", invoke);
  }
  @Test
  public void findSuperMethodTest() throws Throwable {
    // 查找父类的方法
    final MethodHandle handle = MethodHandleUtil.findMethod(BigDuck.class, "quack",
        MethodType.methodType(String.class));
    Assert.assertNotNull(handle);
    final String invoke = (String) handle.invoke(new BigDuck());
    Assert.assertEquals("Quack", invoke);
  }
  @Test
  public void findPrivateStaticMethodTest() throws Throwable {
    final MethodHandle handle = MethodHandleUtil.findMethod(BigDuck.class, "getPrivateStaticValue",
        MethodType.methodType(String.class));
    Assert.assertNotNull(handle);
    final String invoke = (String) handle.invoke();
    Assert.assertEquals("private static value", invoke);
  }
  interface Duck {
    default String quack() {
      return "Quack";
    }
    static String getDuck(int count){
      return "Duck " + count;
    }
  }
  static class BigDuck implements Duck{
    public int getSize(){
      return 36;
    }
    @SuppressWarnings("unused")
    private String getPrivateValue(){
      return "private value";
    }
    @SuppressWarnings("unused")
    private static String getPrivateStaticValue(){
      return "private static value";
    }
  }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值