Java常用工具类
CommonUtil
通用工具类
public class CommonUtil {
/**
* 通过传入的实体类,将其中有值的属性转换成判断条件
*
* @param t
* @param <T>
* @return
*/
public static <T> QueryWrapper<T> getQueryWrapper(T t) {
Class<?> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
for (Field field : fields) {
String fieldName;
PropertyDescriptor pd;
Method getter;
Object value;
try {
// 获取字段名称
fieldName = field.getName();
if (fieldName.equals("serialVersionUID")) {
continue;
}
// 使用Java反射,获取字段的属性描述器
pd = new PropertyDescriptor(fieldName, clazz);
// 获取字段的get方法
getter = pd.getReadMethod();
// 调用字段的get方法,获取字段的值
value = getter.invoke(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 如果字段的值不为空,则添加查询条件
if (value != null) {
// 判断字段类型是否为String型,如果是,则使用like查询
if (String.class.equals(field.getType()) && StringUtils.hasText((String) value)) {
queryWrapper.like(fieldName, (String) value);
} else {
queryWrapper.eq(fieldName, value);
}
}
}
return queryWrapper;
}
/**
* 下划线命名法转换成驼峰命名法
*
* @param underscoreName
* @return
*/
public static String convertToCamelCase(String underscoreName) {
StringBuilder result = new StringBuilder();
boolean nextUpperCase = false;
for (int i = 0; i < underscoreName.length(); i++) {
char currentChar = underscoreName.charAt(i);
if (currentChar == '_') {
nextUpperCase = true;
} else {
if (nextUpperCase) {
result.append(Character.toUpperCase(currentChar));
nextUpperCase = false;
} else {
result.append(Character.toLowerCase(currentChar));
}
}
}
return result.toString();
}
}
JwtUtil
Jwt工具类
public class JwtUtil {
// 密钥
private static final String secretKey = "HfkjksFKLJISJFKLFKWJFQFIQWIOFJQOFFQGGSDGFFJIQOEUFIEJFIOQWEFHFQOK5FKOIQWUFFEFE423FIQEOFJHUEWHFKASKDLQWJIFSJDJKFHJIJWO";
// token 有效期(毫秒)
private static final long validityPeriod = 3600000 * 6; // 6小时
/**
* 根据实体类生成 token
*
* @param t
* @return
*/
public static <T> String createToken(T t) {
Class<?> clazz = t.getClass();
Field field;
try {
field = clazz.getDeclaredField("id");
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
// 获取当前时间
Date now = new Date();
// 设置过期时间
Date expiration = new Date(now.getTime() + validityPeriod);
// 构建 JWT Token
return Jwts.builder()
.setSubject(field.getName())
.claim("userInfo", t)
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
}
/**
* 校验 token
*
* @param token
* @return
*/
public static boolean verifyToken(String token) {
try {
// 解析 JWT Token
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
// Token 验证成功
return true;
} catch (Exception e) {
// Token 验证失败
return false;
}
}
/**
* 解析 token
*
* @param token
* @return
*/
public static Claims parseToken(String token) {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
}
}
CacheUtil
本地缓存工具类
public class CacheUtil {
/**
* 缓存数据
*/
private final static Map<String, CacheEntity> CACHE_MAP = new ConcurrentHashMap<>();
/**
* 定时器线程池,用于清除过期缓存
*/
private static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
static {
// 注册一个定时线程任务,服务启动1秒之后,每隔500毫秒执行一次
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// 清理过期缓存
clearCache();
}
},1000,3600000,TimeUnit.MILLISECONDS);
}
/**
* 添加缓存
* @param key 缓存键
* @param value 缓存值
*/
public static void put(String key, Object value){
put(key, value, 3600);
}
/**
* 添加缓存
* @param key 缓存键
* @param value 缓存值
* @param expire 缓存时间,单位秒
*/
public static void put(String key, Object value, long expire){
CacheEntity cacheEntity = new CacheEntity();
cacheEntity.setKey(key);
cacheEntity.setValue(value);
if(expire > 0){
Long expireTime = System.currentTimeMillis() + Duration.ofSeconds(expire).toMillis();
// cacheEntity.setExpireTime(expireTime);
}
CACHE_MAP.put(key, cacheEntity);
}
/**
* 获取缓存
* @param key
* @return
*/
public static Object get(String key){
if(CACHE_MAP.containsKey(key)){
return CACHE_MAP.get(key).getValue();
}
return null;
}
/**
* 移除缓存
* @param key
*/
public static void remove(String key){
if(CACHE_MAP.containsKey(key)){
CACHE_MAP.remove(key);
}
}
/**
* 清理过期的缓存数据
*/
private static void clearCache(){
if(!CACHE_MAP.isEmpty()){
return;
}
Iterator<Map.Entry<String, CacheEntity>> iterator = CACHE_MAP.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, CacheEntity> entry = iterator.next();
if(entry.getValue().getExpireTime() != null && entry.getValue().getExpireTime().longValue() > System.currentTimeMillis()){
iterator.remove();
}
}
}
}
DateTimeUtil
日期时间工具类
public class DateTimeUtil {
/**
* 指定日期完后延迟指定天数
* @return
*/
public static LocalDateTime plusDays(LocalDateTime localDateTime,Integer dayNum){
return localDateTime.plusDays(dayNum);
}
/**
* 获取当前日期(年-月-日 时:分:秒)
* @return
*/
public static String currentTime(){
LocalDateTime currentTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return currentTime.format(formatter);
}
/**
* 获取当前日期(年-月-日)
* @return
*/
public static String currentDate(){
LocalDateTime currentTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return currentTime.format(formatter);
}
/**
* 获取当前日期(时:分:秒)
* @return
*/
public static String currentDateTime(){
LocalDateTime currentTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
return currentTime.format(formatter);
}
/**
* 判断两个日期是否在同一天
* @param d1
* @param d2
* @return
*/
public static boolean isSameDate(Date d1, Date d2){
if (d1.getYear()==d2.getYear() && d1.getMonth()==d2.getMonth()&&d1.getDate()==d2.getDate()){
return true;
}
return false;
}
/**
* 获取年
*
* @param dateTime
* @return
*/
public static int getYear(LocalDateTime dateTime) {
return dateTime.getYear();
}
/**
* 获取月份
*
* @param dateTime
* @return
*/
public static int getMonth(LocalDateTime dateTime) {
return dateTime.getMonthValue();
}
/**
* 获取日
*
* @param dateTime
* @return
*/
public static int getDay(LocalDateTime dateTime) {
return dateTime.getDayOfMonth();
}
/**
* 获取小时
*
* @param dateTime
* @return
*/
public static int getHour(LocalDateTime dateTime) {
return dateTime.getHour();
}
/**
* 获取分钟
*
* @param dateTime
* @return
*/
public static int getMinute(LocalDateTime dateTime) {
return dateTime.getMinute();
}
/**
* 获取秒
*
* @param dateTime
* @return
*/
public static int getSecond(LocalDateTime dateTime) {
return dateTime.getSecond();
}
}
注:都是本人自己写的,若有Bug或不足之处可在评论区留言,我会积极改进,后续持续更新工具类