fix : Replenish toolkit(#725)

pull/762/head
pizihao 3 years ago
parent 75cc66ec02
commit 2b99a47bcb

@ -91,6 +91,16 @@ public class Assert {
}
}
public static void notBlank(String str, String message) {
if (StringUtil.isNotBlank(str)) {
throw new IllegalArgumentException(message);
}
}
public static void notBlank(String str) {
notBlank(str, "[Assertion failed] - this string must not be blank");
}
public static void hasText(String text, String message) {
if (!StringUtils.hasText(text)) {
throw new IllegalArgumentException(message);

@ -0,0 +1,141 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.web.exception.IllegalException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Bean util.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class BeanUtil {
/**
* copyProperties
*
* @param source source obj
* @param target target obj
* @param <T> target type
* @param <S> source type
* @return T
*/
public static <T, S> T copyProperties(S source, T target) {
return copyProperties(source, target, (String) null);
}
/**
* copyProperties
*
* @param source source obj
* @param target target obj
* @param ignoreProperties ignore name
* @param <T> target type
* @param <S> source type
* @return T
*/
public static <T, S> T copyProperties(S source, T target, String... ignoreProperties) {
BeanUtils.copyProperties(source, target, ignoreProperties);
return target;
}
public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz, boolean toCamelCase) {
if (clazz == null) {
return null;
}
try {
T newInstance = clazz.newInstance();
return mapToBean(map, newInstance, toCamelCase);
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalException("do not create instance for " + clazz.getName(), e);
}
}
/**
* map to bean
*
* @param map map
* @param bean obj bean
* @param toCamelCase format to camel case
* @param <T> bean type
* @return T
*/
public static <T> T mapToBean(Map<String, Object> map, T bean, boolean toCamelCase) {
if (bean == null) {
return null;
}
if (map.isEmpty()) {
return bean;
}
Class<?> clazz = bean.getClass();
map.forEach((s, o) -> {
String name = toCamelCase ? StringUtil.toUnderlineCase(s) : s;
Method method = setter(clazz, name);
if (method != null) {
ReflectUtil.invoke(bean, method, o);
}
});
return bean;
}
/**
* getter for properties
*
* @param o obj
* @param propertiesName name
* @return Method for get
*/
public static Method getter(Class<?> o, String propertiesName) {
if (o == null) {
return null;
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o);
return descriptor.getReadMethod();
} catch (IntrospectionException e) {
throw new IllegalException("not find getter for" + propertiesName + "in" + o.getName(), e);
}
}
/**
* setter for properties
*
* @param o obj
* @param propertiesName name
* @return Method for set
*/
public static Method setter(Class<?> o, String propertiesName) {
if (o == null) {
return null;
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o);
return descriptor.getWriteMethod();
} catch (IntrospectionException e) {
throw new IllegalException("not find setter for" + propertiesName + "in" + o.getName(), e);
}
}
}

@ -17,8 +17,6 @@
package cn.hippo4j.common.toolkit;
import cn.hutool.core.util.StrUtil;
import java.util.HashSet;
import java.util.Set;
@ -42,7 +40,7 @@ public class BooleanUtil {
* @return
*/
public static boolean toBoolean(String valueStr) {
if (StrUtil.isNotBlank(valueStr)) {
if (StringUtil.isNotBlank(valueStr)) {
valueStr = valueStr.trim().toLowerCase();
return TREE_SET.contains(valueStr);
}

@ -17,10 +17,8 @@
package cn.hippo4j.common.toolkit;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/**
* Collection util.
@ -123,4 +121,19 @@ public class CollectionUtil {
public static boolean isNotEmpty(Collection<?> collection) {
return !isEmpty(collection);
}
/**
* to list
*
* @param ts elements
* @param <T> type
* @return List
*/
public static <T> List<T> toList(T... ts) {
if (ts == null || ts.length == 0) {
return new ArrayList<>();
}
return Arrays.stream(ts)
.collect(Collectors.toList());
}
}

@ -0,0 +1,76 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.toolkit;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
/**
* date and time util
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DateUtil {
/**
* get time zone for this JVM
*/
private static final TimeZone TIME_ZONE = TimeZone.getDefault();
public static final String NORM_DATE_PATTERN = "yyyy-MM-dd";
public static final String NORM_TIME_PATTERN = "HH:mm:ss";
public static final String NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this <tt>Date</tt> object.
*
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this date.
*/
public static long getTime(LocalDateTime date) {
return getTime(date, TIME_ZONE.toZoneId());
}
public static long getTime(LocalDateTime date, ZoneId zoneId) {
return date.atZone(zoneId).toInstant().toEpochMilli();
}
/**
* modify format to date
*
* @param date date
* @param normTimePattern PATTERN
* @return String
*/
public static String format(Date date, String normTimePattern) {
SimpleDateFormat zoneFormat = new SimpleDateFormat(normTimePattern);
return zoneFormat.format(date);
}
}

@ -17,12 +17,15 @@
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.web.exception.IllegalException;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
/**
* File util;
@ -48,4 +51,38 @@ public class FileUtil {
}
return resultReadStr;
}
public static List<String> readLines(String path, Charset charset) {
List<String> strList = new ArrayList<>();
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
ClassPathResource classPathResource = new ClassPathResource(path);
try {
inputStreamReader = new InputStreamReader(classPathResource.getInputStream(), charset);
bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
strList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
throw new IllegalException("file read error");
} finally {
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
throw new IllegalException("file read error");
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
throw new IllegalException("file read error");
}
}
}
return strList;
}
}

@ -41,7 +41,7 @@ public class MessageConvert {
MessageWrapper wrapper = new MessageWrapper();
wrapper.setResponseClass(message.getClass());
wrapper.setMessageType(message.getMessageType());
List<Map<String, Object>> messageMapList = new ArrayList();
List<Map<String, Object>> messageMapList = new ArrayList<>();
List<Message> messages = message.getMessages();
messages.forEach(each -> {
String eachVal = JSONUtil.toJSONString(each);

@ -17,22 +17,27 @@
package cn.hippo4j.common.toolkit;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.ClassUtil;
import cn.hippo4j.common.web.exception.IllegalException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Reflect util.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ReflectUtil {
private static final Map<Class<?>, Field[]> FIELDS_CACHE = new ConcurrentHashMap();
private static final Map<Class<?>, Field[]> FIELDS_CACHE = new ConcurrentHashMap<>();
public static Object getFieldValue(Object obj, String fieldName) {
if (null == obj || StringUtil.isBlank(fieldName)) {
@ -55,7 +60,7 @@ public class ReflectUtil {
result = field.get(obj);
} catch (IllegalAccessException e) {
String exceptionMsg = String.format("IllegalAccess for %s.%s", field.getDeclaringClass(), field.getName());
throw new RuntimeException(exceptionMsg, e);
throw new IllegalException(exceptionMsg, e);
}
return result;
}
@ -69,7 +74,7 @@ public class ReflectUtil {
public static Field getField(Class<?> beanClass, String name) throws SecurityException {
final Field[] fields = getFields(beanClass);
return ArrayUtil.firstMatch((field) -> name.equals(getFieldName(field)), fields);
return ArrayUtil.firstMatch(field -> name.equals(getFieldName(field)), fields);
}
public static Field[] getFields(Class<?> beanClass) throws SecurityException {
@ -109,32 +114,114 @@ public class ReflectUtil {
return field.getName();
}
public static void setFieldValue(Object obj, String fieldName, Object value) throws UtilException {
cn.hutool.core.lang.Assert.notNull(obj);
cn.hutool.core.lang.Assert.notBlank(fieldName);
public static void setFieldValue(Object obj, String fieldName, Object value) throws IllegalException {
Assert.notNull(obj);
Assert.notBlank(fieldName);
final Field field = getField((obj instanceof Class) ? (Class<?>) obj : obj.getClass(), fieldName);
cn.hutool.core.lang.Assert.notNull(field, "Field [{}] is not exist in [{}]", fieldName, obj.getClass().getName());
Assert.notNull(field, "Field [" + fieldName + "] is not exist in [" + obj.getClass().getName() + "]");
setFieldValue(obj, field, value);
}
public static void setFieldValue(Object obj, Field field, Object value) throws UtilException {
cn.hutool.core.lang.Assert.notNull(field, "Field in [{}] not exist !", obj);
public static void setFieldValue(Object obj, Field field, Object value) throws IllegalException {
Assert.notNull(field, "Field in [" + obj + "] not exist !");
final Class<?> fieldType = field.getType();
if (null != value) {
if (!fieldType.isAssignableFrom(value.getClass())) {
final Object targetValue = Convert.convert(fieldType, value);
final Object targetValue = cast(fieldType, value);
if (null != targetValue) {
value = targetValue;
}
}
} else {
value = ClassUtil.getDefaultValue(fieldType);
value = getDefaultValue(fieldType);
}
setAccessible(field);
try {
field.set(obj instanceof Class ? null : obj, value);
} catch (IllegalAccessException e) {
throw new UtilException(e, "IllegalAccess for {}.{}", obj, field.getName());
throw new IllegalException("IllegalAccess for " + obj + "." + field.getName(), e);
}
}
/**
* find the method associated with the method name
*
* @param clazz the class
* @param methodName retrieves the method name
* @param arguments matched parameters class
* @return find method
*/
public static Method getMethodByName(Class<?> clazz, String methodName, Class<?>... arguments) {
try {
if (Objects.nonNull(clazz) && Objects.nonNull(methodName)) {
return clazz.getMethod(methodName, arguments);
}
} catch (NoSuchMethodException e) {
throw new IllegalException(e);
}
return null;
}
/**
* Cast the value to the type <br>
* If a ClassCastException occurs, return null
*
* @param clazz Cast class
* @param value The cast value
* @return The value after the cast is completed
*/
public static Object cast(Class<?> clazz, Object value) {
try {
return clazz.cast(value);
} catch (ClassCastException e) {
return null;
}
}
/**
* the default value is obtained if it is a primitive type, and NULL if it is not
*
* @param clazz clazz
* @return default value
*/
public static Object getDefaultValue(Class<?> clazz) {
if (Objects.isNull(clazz) || !clazz.isPrimitive()) {
return null;
}
if (long.class.isAssignableFrom(clazz)) {
return 0L;
} else if (int.class.isAssignableFrom(clazz)) {
return 0;
} else if (short.class.isAssignableFrom(clazz)) {
return (short) 0;
} else if (char.class.isAssignableFrom(clazz)) {
return (char) 0;
} else if (byte.class.isAssignableFrom(clazz)) {
return (byte) 0;
} else if (double.class.isAssignableFrom(clazz)) {
return 0D;
} else if (float.class.isAssignableFrom(clazz)) {
return 0f;
} else if (boolean.class.isAssignableFrom(clazz)) {
return false;
}
return null;
}
/**
* invoke
*
* @param obj the obj
* @param method the method
* @param arguments parameters
* @return result for zhe method
*/
@SuppressWarnings("unchecked")
public static <T> T invoke(Object obj, Method method, Object... arguments) {
try {
return (T) method.invoke(obj, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalException(e);
}
}
}

@ -29,7 +29,7 @@ import java.util.function.Supplier;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Singleton {
private static final ConcurrentHashMap<String, Object> SINGLE_OBJECT_POOL = new ConcurrentHashMap();
private static final ConcurrentHashMap<String, Object> SINGLE_OBJECT_POOL = new ConcurrentHashMap<>();
/**
* Get a singleton object by key.

@ -17,6 +17,9 @@
package cn.hippo4j.common.toolkit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* String util.
*/
@ -191,4 +194,57 @@ public class StringUtil {
}
return sb.toString();
}
/**
* Replace a portion of the string, replacing all found
*
* @param str A string to operate on
* @param searchStr The replaced string
* @param replaceStr The replaced string
* @return Replace the result
*/
public static String replace(String str, String searchStr, String replaceStr) {
return Pattern
.compile(searchStr, Pattern.LITERAL)
.matcher(str)
.replaceAll(Matcher.quoteReplacement(replaceStr));
}
/**
* Tests if this string starts with the specified prefix.
*
* @param str this str
* @param prefix the suffix
* @return Whether the prefix exists
*/
public static boolean startWith(String str, String prefix) {
if (isEmpty(str)) {
return false;
}
return str.startsWith(prefix);
}
/**
* get the string before the delimiter
*
* @param str string
* @param symbol separator
* @return String
*/
public static String subBefore(String str, String symbol) {
if (isEmpty(str) || symbol == null) {
return str;
}
if (symbol.isEmpty()) {
return EMPTY;
}
int pos = str.indexOf(symbol);
if (-1 == pos) {
return str;
}
if (0 == pos) {
return EMPTY;
}
return str.substring(0, pos);
}
}

@ -28,7 +28,7 @@ import java.util.Optional;
*/
public class UserContext {
private static final ThreadLocal<User> USER_THREAD_LOCAL = new ThreadLocal();
private static final ThreadLocal<User> USER_THREAD_LOCAL = new ThreadLocal<>();
public static void setUserInfo(String username, String userRole) {
USER_THREAD_LOCAL.set(new User(username, userRole));

@ -0,0 +1,47 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.web.exception;
/**
* A generic exception to handle illegal operations
*/
public class IllegalException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public IllegalException() {
super();
}
public IllegalException(String message) {
super(message);
}
public IllegalException(Throwable e) {
super(e.getMessage(), e);
}
public IllegalException(String message, Throwable throwable) {
super(message, throwable);
}
public IllegalException(String message, Throwable throwable, boolean enableSuppression, boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
}
}

@ -0,0 +1,73 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.toolkit;
import lombok.Getter;
import lombok.Setter;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class BeanUtilTest {
@Test
public void testMapToBean() {
Map<String, Object> map = new HashMap<>();
map.put("name", "Test");
map.put("status", 12);
Customer customer = BeanUtil.mapToBean(map, Customer.class, true);
Assert.assertEquals("Test", customer.getName());
Assert.assertEquals(Integer.valueOf(12), customer.getStatus());
}
@Test
public void testGetter() {
Method name = BeanUtil.getter(Customer.class, "name");
Assert.assertEquals("getName", name.getName());
}
@Test
public void testSetter() {
Method name = BeanUtil.setter(Customer.class, "name");
Assert.assertEquals("setName", name.getName());
}
@Getter
@Setter
static class Customer {
String name;
Integer status;
}
@Getter
@Setter
static class PreCustomer {
String name;
Integer status;
}
}

@ -17,19 +17,20 @@
package cn.hippo4j.common.toolkit;
import org.junit.Assert;
import org.junit.Test;
public class BooleanUtilTest {
@Test
public void assertToBoolean() {
Assert.isTrue(BooleanUtil.toBoolean("true"));
Assert.isTrue(BooleanUtil.toBoolean("yes"));
Assert.isTrue(BooleanUtil.toBoolean("1"));
Assert.assertTrue(BooleanUtil.toBoolean("true"));
Assert.assertTrue(BooleanUtil.toBoolean("yes"));
Assert.assertTrue(BooleanUtil.toBoolean("1"));
}
@Test
public void assertIsTrue() {
Assert.isTrue(BooleanUtil.isTrue(true));
Assert.assertTrue(BooleanUtil.isTrue(true));
}
}

@ -18,6 +18,10 @@
package cn.hippo4j.common.toolkit;
import org.junit.Test;
import org.junit.Assert;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class FileUtilTest {
@ -25,7 +29,7 @@ public class FileUtilTest {
public void assertReadUtf8String() {
String testFilePath = "test/test_utf8.txt";
String contentByFileUtil = FileUtil.readUtf8String(testFilePath);
Assert.notEmpty(contentByFileUtil);
Assert.assertFalse(contentByFileUtil.isEmpty());
}
@Test
@ -36,6 +40,13 @@ public class FileUtilTest {
"empty line next" + linebreaks;
String testFilePath = "test/test_utf8.txt";
String contentByFileUtil = FileUtil.readUtf8String(testFilePath);
Assert.isTrue(testText.equals(contentByFileUtil));
Assert.assertTrue(testText.equals(contentByFileUtil));
}
@Test
public void assertReadLines() {
String testFilePath = "test/test_utf8.txt";
List<String> readLines = FileUtil.readLines(testFilePath, StandardCharsets.UTF_8);
Assert.assertEquals(3, readLines.size());
}
}

@ -18,10 +18,12 @@
package cn.hippo4j.common.toolkit;
import lombok.Getter;
import lombok.Setter;
import org.junit.Test;
import org.junit.Assert;
import java.lang.reflect.Field;
import java.util.Objects;
import java.lang.reflect.Method;
public class ReflectUtilTest {
@ -29,10 +31,10 @@ public class ReflectUtilTest {
public void getFieldValueTest() {
TestSubClass testSubClass = new TestSubClass();
Object privateField = ReflectUtil.getFieldValue(testSubClass, "privateField");
Assert.isTrue(Objects.equals("privateField", privateField));
Assert.assertEquals("privateField", privateField);
Object field = ReflectUtil.getFieldValue(testSubClass, "field");
Assert.isTrue(Objects.equals("field", field));
Assert.assertEquals("field", field);
}
@ -42,57 +44,99 @@ public class ReflectUtilTest {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Object privateFieldVal = ReflectUtil.getFieldValue(testSubClass, privateField);
Assert.isTrue(Objects.equals("privateField", privateFieldVal));
Assert.assertEquals("privateField", privateFieldVal);
}
@Test
public void getFieldTest() {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Assert.notNull(privateField);
Assert.assertNotNull(privateField);
Field field = ReflectUtil.getField(TestSubClass.class, "field");
Assert.notNull(field);
Assert.assertNotNull(field);
}
@Test
public void getFieldsTest() {
Field[] fields = ReflectUtil.getFields(TestSubClass.class);
Assert.isTrue(Objects.equals(4, fields.length));
Assert.assertEquals(4, fields.length);
}
@Test
public void getFieldsDirectlyTest() {
Field[] fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, false);
Assert.isTrue(Objects.equals(2, fields.length));
Assert.assertEquals(2, fields.length);
fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, true);
Assert.isTrue(Objects.equals(4, fields.length));
Assert.assertEquals(4, fields.length);
}
@Test
public void getFieldNameTest() {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
String fieldName = ReflectUtil.getFieldName(privateField);
Assert.notNull(fieldName);
Assert.assertNotNull(fieldName);
Field subField = ReflectUtil.getField(TestSubClass.class, "subField");
String subfieldName = ReflectUtil.getFieldName(subField);
Assert.notNull(subfieldName);
Assert.assertNotNull(subfieldName);
}
@Test
public void setFieldValueTest() {
TestClass testClass = new TestClass();
ReflectUtil.setFieldValue(testClass, "field", "fieldVal");
Assert.isTrue(Objects.equals("fieldVal", testClass.getField()));
Assert.assertEquals("fieldVal", testClass.getField());
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
ReflectUtil.setFieldValue(testClass, privateField, "privateFieldVal");
Assert.isTrue(Objects.equals("privateFieldVal", testClass.getPrivateField()));
Assert.assertEquals("privateFieldVal", testClass.getPrivateField());
}
@Test
public void castTest() {
TestClass testClass = new TestSubClass();
Object cast = ReflectUtil.cast(TestSubClass.class, testClass);
Assert.assertTrue(cast instanceof TestSubClass);
}
@Test
public void getDefaultValueTest() {
Object defaultValue = ReflectUtil.getDefaultValue(Long.class);
Assert.assertNull(defaultValue);
Object primitiveValueLong = ReflectUtil.getDefaultValue(long.class);
Assert.assertEquals(0L, primitiveValueLong);
Object primitiveValueInt = ReflectUtil.getDefaultValue(int.class);
Assert.assertEquals(0, primitiveValueInt);
Object primitiveValueFloat = ReflectUtil.getDefaultValue(float.class);
Assert.assertEquals(0f, primitiveValueFloat);
Object primitiveValueShort = ReflectUtil.getDefaultValue(short.class);
Assert.assertEquals((short) 0, primitiveValueShort);
Object primitiveValueChar = ReflectUtil.getDefaultValue(char.class);
Assert.assertEquals((char) 0, primitiveValueChar);
Object primitiveValueDouble = ReflectUtil.getDefaultValue(double.class);
Assert.assertEquals(0D, primitiveValueDouble);
Object primitiveValueBoolean = ReflectUtil.getDefaultValue(boolean.class);
Assert.assertEquals(false, primitiveValueBoolean);
}
@Test
public void getMethodByNameTest() {
Method field = ReflectUtil.getMethodByName(TestClass.class, "getPrivateField", String.class);
Assert.assertNotNull(field);
}
@Test
public void invokeTest() {
TestClass testClass = new TestClass();
Method method = ReflectUtil.getMethodByName(TestClass.class, "getPrivateField");
String invoke = ReflectUtil.invoke(testClass, method);
Assert.assertEquals(invoke, "privateField");
}
@Getter
@Setter
static class TestClass {
private String privateField;

@ -18,8 +18,7 @@
package cn.hippo4j.common.toolkit;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
public class ThreadUtilTest {
@ -32,11 +31,11 @@ public class ThreadUtilTest {
final Thread result = ThreadUtil.newThread(runnable, "name", false);
// Verify the results
Assert.notNull(result);
Assert.assertNotNull(result);
}
@Test
public void testSleep() {
assertTrue(ThreadUtil.sleep(0L));
Assert.assertTrue(ThreadUtil.sleep(0L));
}
}

@ -17,11 +17,8 @@
package cn.hippo4j.common.toolkit;
import cn.hutool.core.util.ReflectUtil;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
public class UserContextTest {
private static final String USERNAME = "test";

Loading…
Cancel
Save