This commit is contained in:
lu7213 committed 2026-03-03 09:39:33 +08:00
1 parent 68a2b4f68c
commit 7cd697187c
308 files changed
+30454 -75

No files matched your search

@@ -20,7 +20,7 @@ public class QiNiuRefreshTokenTask {
private IQiniuService qiniuService;
// @Scheduled(cron = "0/10 * * * * ?")
@Scheduled(cron = "* 0/10 * * * ?")
@Scheduled(cron = "0 */10 * * * ?")
public void refreshQiniuToken() {
qiniuService.refreshQiniuToken();
@@ -0,0 +1,102 @@
package com.luqj.util;
/**
* 算术符号
* @author chenzm
*/
public enum ArithmeticEnum {
/**左括号**/
lb("(", "左括号", -1),
/**右括号**/
rb(")", "右括号", -1),
/**乘**/
multiply("*", "乘", -3),
/**除**/
division("/", "除", -3),
/**加**/
addition("+", "加", -4),
/**减**/
subtract("-", "减", -4),
/**大于**/
gt(">", "大于", -6),
/**小于**/
lt("<", "小于", -6),
/**大于等于**/
gte(">=", "大于等于", -6),
/**小于等于**/
lte("<=", "小于等于", -6);
/**符号**/
private String symbol;
/**优先级**/
private int priority;
private String desc;
private ArithmeticEnum(String symbol, String desc, int priority) {
this.symbol = symbol;
this.desc = desc;
this.priority = priority;
}
public boolean isEqualBySymbol(String c) {
return this.getSymbol().equals(c);
}
public boolean isEqualBySymbol(char c) {
return this.getSymbol().equals("" + c);
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
/**
* 获取符号等级
*/
public static int getSymbolLevel(String c) {
return getArithmeticEnum(c).getPriority();
}
public static ArithmeticEnum getArithmeticEnum(String c) {
for(ArithmeticEnum t : ArithmeticEnum.values()) {
if(t.getSymbol().equals(c)) {
return t;
}
}
return null;
}
public static boolean containsKey(String c) {
if(getArithmeticEnum(c) != null) {
return true;
}
return false;
}
}
@@ -0,0 +1,567 @@
package com.luqj.util;
import com.luqj.util.parse.SymbolSet;
import java.util.NoSuchElementException;
/**
* 字符缓存
*/
public class CharBuffer {
transient int size = 0;
transient Node first;
transient Node last;
transient int modCount = 0;
public CharBuffer() {
}
public CharBuffer(String str) {
for(char c : str.toCharArray()) {
this.add(c);
}
}
public CharBuffer(char[] chs) {
for(char c : chs) {
this.add(c);
}
}
public String asString() {
return new String(this.toArray());
}
public void addStr(String str) {
for(char c : str.toCharArray()) {
this.add(c);
}
}
/**
* Links e as first element.
*/
private void linkFirst(char e) {
final Node f = first;
final Node newNode = new Node(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
void linkLast(char e) {
final Node l = last;
final Node newNode = new Node(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(char e, Node succ) {
// assert succ != null;
final Node pred = succ.prev;
final Node newNode = new Node(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
/**
* Unlinks non-null first node f.
*/
private char unlinkFirst(Node f) {
// assert f == first && f != null;
final char element = f.item;
final Node next = f.next;
//f.item = ' ';
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* Unlinks non-null last node l.
*/
private char unlinkLast(Node l) {
// assert l == last && l != null;
final char element = l.item;
final Node prev = l.prev;
//l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* Unlinks non-null node x.
*/
char unlink(Node x) {
// assert x != null;
final char element = x.item;
final Node next = x.next;
final Node prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
//x.item = null;
size--;
modCount++;
return element;
}
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public char getFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public char getLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public char removeFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public char removeLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(char e) {
linkFirst(e);
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(char e) {
linkLast(e);
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by
*/
public boolean add(char e) {
linkLast(e);
return true;
}
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node x = first; x != null; ) {
Node next = x.next;
//x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
// Positional Access Operations
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public char get(int index) {
//checkElementIndex(index);
return node(index).item;
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/*private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}*/
/* private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}*/
/**
* Returns the (non-null) Node at the specified element index.
*/
Node node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public char poll() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public char remove() {
return removeFirst();
}
/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @since 1.5
*/
public boolean offer(char e) {
return add(e);
}
// Deque operations
/**
* Inserts the specified element at the front of this list.
*
* @param e the element to insert
* @since 1.6
*/
public boolean offerFirst(char e) {
addFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this list.
*
* @param e the element to insert
* @since 1.6
*/
public boolean offerLast(char e) {
addLast(e);
return true;
}
/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public char peekFirst() {
final Node f = first;
return (f == null) ? null : f.item;
}
public boolean isEmpty() {
return size() == 0;
}
/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public char peekLast() {
final Node l = last;
return (l == null) ? null : l.item;
}
/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public char pollFirst() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public char pollLast() {
final Node l = last;
return (l == null) ? null : unlinkLast(l);
}
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(char e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public char pop() {
return removeFirst();
}
private static class Node {
char item;
Node next;
Node prev;
Node(Node prev, char element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list
* in proper sequence
*/
public char[] toArray() {
char[] result = new char[size];
int i = 0;
for (Node x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
public char[] subArray(int start,int end){
if (start < 0)
throw new ArrayIndexOutOfBoundsException(start);
if (end > size)
throw new StringIndexOutOfBoundsException(end);
if (start > end)
throw new ArrayIndexOutOfBoundsException(end - start);
int size = end-start;
char[] result = new char[size];
int iStart = 0;
for (Node x = first; x != null && iStart < end; x = x.next){
if(iStart >= start){
result[iStart - start] = x.item;
}
iStart++;
}
return result;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (Node x = first; x != null; x = x.next)
sb.append(x.item+",");
return "["+sb.toString()+"]";
}
/**
* 是否是文本
* @return
*/
public boolean isText() {
boolean isNull = true;
for(char c : this.toArray()) {
if(c != SymbolSet.SYMBOL_NULL) {
isNull = false;
break;
}
}
return this.size() > 0 && !isNull;
}
private static final long serialVersionUID = 876323262645176354L;
}
@@ -0,0 +1,137 @@
package com.luqj.util;
import com.luqj.util.assertion.Assert;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileSystemUtil {
private static final char SYSTEM_SEPARATOR = File.separatorChar;
private static final char WINDOWS_SEPARATOR = '\\';
/**
* 递归获取指定目录下的所有文件
* @param dir
* @param filterDir 子目录是否返回在集合中
* @return
*/
public static final List<File> getAllFiles(File dir,boolean filterDir,FileFilter filter){
Assert.logic(dir.isDirectory() && dir.canRead(),dir+"必须是目录且可读");
List<File> result = new ArrayList<File>();
File[] files = null;
if(filter != null){
files = dir.listFiles(filter);
}else{
files = dir.listFiles();
}
for (File file : files) {
if(file.isDirectory()){
if(filterDir){
result.add(file);
}
result.addAll(getAllFiles(file, filterDir, filter));
}else{
result.add(file);
}
}
return result;
}
/**
* 强制删除文件
* 引用org.apache.commons.io.FileUtils代码
* @param file
* @throws IOException
*/
public static void forceDelete(File file) throws IOException {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
boolean filePresent = file.exists();
if (!file.delete()) {
if (!filePresent){
throw new FileNotFoundException("File does not exist: " + file);
}
String message =
"Unable to delete file: " + file;
throw new IOException(message);
}
}
}
public static void deleteDirectory(File directory) throws IOException {
if (!directory.exists()) {
return;
}
if (!isSymlink(directory)) {
cleanDirectory(directory);
}
if (!directory.delete()) {
String message =
"Unable to delete directory " + directory + ".";
throw new IOException(message);
}
}
public static boolean isSymlink(File file) throws IOException {
if (file == null) {
throw new NullPointerException("File must not be null");
}
if (SYSTEM_SEPARATOR == WINDOWS_SEPARATOR) {
return false;
}
File fileInCanonicalDir = null;
if (file.getParent() == null) {
fileInCanonicalDir = file;
} else {
File canonicalDir = file.getParentFile().getCanonicalFile();
fileInCanonicalDir = new File(canonicalDir, file.getName());
}
if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) {
return false;
} else {
return true;
}
}
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (File file : files) {
try {
forceDelete(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
}
}
@@ -0,0 +1,322 @@
package com.luqj.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created: 2016/7/5.
* Author: Qiannan Lu
*/
public class IdentificationNumberUtils {
private final static Logger logger = LoggerFactory.getLogger(IdentificationNumberUtils.class);
/**
* 获取身份证号的出生日期字符串
*
* @param idCard 身份证号
* @return 出生日期字符串
*/
public static String birthday(String idCard) {
if (StringUtils.isBlank(idCard)
|| idCard.length() <= 14) {
logger.error("传入身份证号{}位数不对!", idCard);
return null;
}
return id15ToId18(idCard).substring(6, 14);
}
/**
* 获取身份证号的出生日期
*
* @param idCard 身份证号
* @return 出生日期
*/
public static Date birthDate(String idCard) {
String birthDay = birthday(idCard);
if (birthDay == null) return null;
try {
return new SimpleDateFormat("yyyyMMdd").parse(birthDay);
} catch (Exception e) {
logger.error("提取身份证号{}出生日期出错", idCard, e);
return null;
}
}
/**
* 获取身份证号的年份信息
*
* @param idCard 身份证号
* @return 年份信息
*/
public static String year(String idCard) {
Calendar calendar = getBirthDateCalendar(idCard);
return calendar == null ? null : Integer.toString(calendar.get(Calendar.YEAR));
}
/**
* 获取身份证号的月份信息 从1月开始
*
* @param idCard 身份证号
* @return 月份信息
*/
public static String month(String idCard) {
Calendar calendar = getBirthDateCalendar(idCard);
return calendar == null ? null : Integer.toString(calendar.get(Calendar.MONTH) + 1);
}
/**
* 获取身份证号的日期信息 月份中的日期
*
* @param idCard 身份证号
* @return 日期信息
*/
public static String day(String idCard) {
Calendar calendar = getBirthDateCalendar(idCard);
return calendar == null ? null : Integer.toString(calendar.get(Calendar.DATE));
}
/**
* 获取身份证号的日期信息 一年中的日期
*
* @param idCard 身份证号
* @return 日期信息
*/
public static String dayOfYear(String idCard) {
Calendar calendar = getBirthDateCalendar(idCard);
return calendar == null ? null : Integer.toString(calendar.get(Calendar.DAY_OF_YEAR));
}
/**
* 获取身份证号的出生日期信息
*
* @param idCard 身份证号
* @return 出生日期
*/
private static Calendar getBirthDateCalendar(String idCard) {
Date birthDate = birthDate(idCard);
if (birthDate == null) return null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(birthDate);
return calendar;
}
/**
* 18位身份证转15位.
*
* @param id18 18为身份证号
* @return 15位身份证号
*/
public static String id18ToId15(String id18) {
return id18.substring(0, 6) + id18.substring(8, 17);
}
/**
* 15位身份证转18位.
*
* @param id15 15位身份证号
* @return 18位身份证号
*/
public static String id15ToId18(String id15) {
int IdLength = id15.length();
String id18;
switch (IdLength) {
case 15:
String serial = id15.substring(IdLength - 3);
if (serial.equals("996") || serial.equals("997") || serial.equals("998") || serial.equals("999")) {
id18 = id15.substring(0, 6) + "18" + id15.substring(IdLength - 9);
} else {
id18 = id15.substring(0, 6) + "19" + id15.substring(IdLength - 9);
}
id18 = id18 + getIdCheckBit(id18);
break;
case 17:
id18 = id15 + getIdCheckBit(id15);
break;
case 18:
id18 = id15;
break;
default:
id18 = id15;
}
return id18;
}
/**
* 判断传入的字符串是否是身份证号,如果是18位 会判断最后一位标志位
* 如果是15位则返回false
*
* @param idCard 身份证号
* @return 是否是真是身份证号
*/
public static boolean isValid(String idCard) {
boolean isLooksLike = isLooksLike(idCard);
if (isLooksLike && idCard.length() == 18) {
String x = getIdCheckBit(idCard);
if (x.equals("" + idCard.charAt(17)))
return true;
}
return false;
}
/**
* 判断传入的字符串(15位或者18位)是否是身份证号,其他直接返回false
* @param idCard 身份证号
* @return 是否是真是身份证号
*/
public static boolean checkIsIdCard(String idCard) {
boolean isLooksLike = isLooksLike(idCard);
if (isLooksLike && idCard.length() == 18) {
String x = getIdCheckBit(idCard);
if (x.equals("" + idCard.charAt(17)))
return true;
}
if (isLooksLike && idCard.length() == 15) {
String x = getIdCheckBit(id15ToId18(idCard));
if (x.equals("" + id15ToId18(idCard).charAt(17)))
return true;
}
return false;
}
/**
* 判断传入的字符串是否像是身份证号,只会判断出身年月信息
*
* @param idCard 身份证号
* @return 是否像身份证号
*/
public static boolean isLooksLike(String idCard) {
if (idCard.length() == 15) {
String birthday = idCard.substring(6, 12);
return isYear(birthday.substring(0, 2)) && isMonth(birthday.substring(2, 4)) && isDay(birthday.substring(4, 6));
} else if (idCard.length() == 18) {
String birthday = idCard.substring(6, 14);
return isYear(birthday.substring(0, 4)) && isMonth(birthday.substring(4, 6)) && isDay(birthday.substring(6, 8));
}
return false;
}
/**
* 判断数字是否符合年份
*
* @param year 数字
*/
private static boolean isYear(String year) {
if (year.length() == 4) {
try {
int y = Integer.parseInt(year);
if (y < 1900 || y > 2100) {
return false;
}
} catch (Exception e) {
return false;
}
}
return true;
}
/**
* 判断数字是否符合月份
*
* @param month 数字
*/
private static boolean isMonth(String month) {
try {
int m = Integer.parseInt(month);
if (m < 1 || m > 12) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断数字是否符合日期
*
* @param day 数字
*/
private static boolean isDay(String day) {
try {
int d = Integer.parseInt(day);
if (d < 1 || d > 31) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 获取18位身份证号的校验位
*
* @param id18 18位身份证号
* @return 校验位
*/
public static String getIdCheckBit(String id18) {
String[] strCheckChar = new String[11];
int[] nWeight = new int[18];
strCheckChar[0] = "1";
strCheckChar[1] = "0";
strCheckChar[2] = "X";
strCheckChar[3] = "9";
strCheckChar[4] = "8";
strCheckChar[5] = "7";
strCheckChar[6] = "6";
strCheckChar[7] = "5";
strCheckChar[8] = "4";
strCheckChar[9] = "3";
strCheckChar[10] = "2";
nWeight[0] = 7;
nWeight[1] = 9;
nWeight[2] = 10;
nWeight[3] = 5;
nWeight[4] = 8;
nWeight[5] = 4;
nWeight[6] = 2;
nWeight[7] = 1;
nWeight[8] = 6;
nWeight[9] = 3;
nWeight[10] = 7;
nWeight[11] = 9;
nWeight[12] = 10;
nWeight[13] = 5;
nWeight[14] = 8;
nWeight[15] = 4;
nWeight[16] = 2;
nWeight[17] = 1;
int sumMulti = 0;
for (int i = 0; i <= 16; i++) {
String ch = id18.substring(i, i + 1);
sumMulti = sumMulti + (Integer.parseInt(ch) * nWeight[i]);
}
int resultMod = sumMulti % 11;
return strCheckChar[resultMod];
}
public static void main(String[] args) {
}
}
@@ -0,0 +1,169 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed 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 com.luqj.util;
import java.io.Serializable;
import java.util.*;
/**
* Simple implementation of {@link MultiValueMap} that wraps a {@link LinkedHashMap},
* storing multiple values in a {@link LinkedList}.
*
* <p>This Map implementation is generally not thread-safe. It is primarily designed
* for data structures exposed from request objects, for use in a single thread only.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
*/
public class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializable {
private static final long serialVersionUID = 3801124242820219131L;
private final Map<K, List<V>> targetMap;
/**
* Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}.
*/
public LinkedMultiValueMap() {
this.targetMap = new LinkedHashMap<K, List<V>>();
}
/**
* Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}
* with the given initial capacity.
* @param initialCapacity the initial capacity
*/
public LinkedMultiValueMap(int initialCapacity) {
this.targetMap = new LinkedHashMap<K, List<V>>(initialCapacity);
}
/**
* Copy constructor: Create a new LinkedMultiValueMap with the same mappings
* as the specified Map.
* @param otherMap the Map whose mappings are to be placed in this Map
*/
public LinkedMultiValueMap(Map<K, List<V>> otherMap) {
this.targetMap = new LinkedHashMap<K, List<V>>(otherMap);
}
// MultiValueMap implementation
public void add(K key, V value) {
List<V> values = this.targetMap.get(key);
if (values == null) {
values = new LinkedList<V>();
this.targetMap.put(key, values);
}
values.add(value);
}
public V getFirst(K key) {
List<V> values = this.targetMap.get(key);
return (values != null ? values.get(0) : null);
}
public void set(K key, V value) {
List<V> values = new LinkedList<V>();
values.add(value);
this.targetMap.put(key, values);
}
public void setAll(Map<K, V> values) {
for (Entry<K, V> entry : values.entrySet()) {
set(entry.getKey(), entry.getValue());
}
}
public Map<K, V> toSingleValueMap() {
LinkedHashMap<K, V> singleValueMap = new LinkedHashMap<K,V>(this.targetMap.size());
for (Entry<K, List<V>> entry : targetMap.entrySet()) {
singleValueMap.put(entry.getKey(), entry.getValue().get(0));
}
return singleValueMap;
}
// Map implementation
public int size() {
return this.targetMap.size();
}
public boolean isEmpty() {
return this.targetMap.isEmpty();
}
public boolean containsKey(Object key) {
return this.targetMap.containsKey(key);
}
public boolean containsValue(Object value) {
return this.targetMap.containsValue(value);
}
public List<V> get(Object key) {
return this.targetMap.get(key);
}
public List<V> put(K key, List<V> value) {
return this.targetMap.put(key, value);
}
public List<V> remove(Object key) {
return this.targetMap.remove(key);
}
public void putAll(Map<? extends K, ? extends List<V>> m) {
this.targetMap.putAll(m);
}
public void clear() {
this.targetMap.clear();
}
public Set<K> keySet() {
return this.targetMap.keySet();
}
public Collection<List<V>> values() {
return this.targetMap.values();
}
public Set<Entry<K, List<V>>> entrySet() {
return this.targetMap.entrySet();
}
@Override
public boolean equals(Object obj) {
return this.targetMap.equals(obj);
}
@Override
public int hashCode() {
return this.targetMap.hashCode();
}
@Override
public String toString() {
return this.targetMap.toString();
}
}
@@ -0,0 +1,153 @@
package com.luqj.util;
import java.util.*;
/**
* Created by lucheng on 2017/8/23.
*/
public class MapSortUtil {
/**
* 使用 Map按key进行排序
*
* @param map
* @return
*/
public static TreeMap<Double, Integer> sortMapByKey(Map<Double, Integer> map, String direction) {
if (map == null || map.isEmpty()) {
return null;
}
TreeMap<Double, Integer> sortMap = new TreeMap<Double, Integer>(
new MapKeyComparator(direction));
sortMap.putAll(map);
return sortMap;
}
/**
* 使用 Map按value进行排序
* @param oriMap
* @param direction
* @return
*/
public static Map<Double, Integer> sortMapByValue(Map<Double, Integer> oriMap, String direction) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<Double, Integer> sortedMap = new LinkedHashMap<Double, Integer>();
List<Map.Entry<Double, Integer>> entryList = new ArrayList<Map.Entry<Double, Integer>>(
oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator(direction));
Iterator<Map.Entry<Double, Integer>> iter = entryList.iterator();
Map.Entry<Double, Integer> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
/**
* 返回某个index对应的值
*
* @param map
* @param index
* @return
*/
public static Double getKeyByIndex(Map<Double, Integer> map, int index) {
int sumCount = 0;
Double result = null;
for (Map.Entry<Double, Integer> newEntry : map.entrySet()) {
Double number = newEntry.getKey();
Integer count = newEntry.getValue();
sumCount += count;
if (index <= sumCount) {
result = number;
break;
}
}
return result;
}
public static class MapKeyComparator implements Comparator<Double> {
private String direction;
public MapKeyComparator(String direction) {
this.direction = direction;
}
@Override
public int compare(Double o1, Double o2) {
if ("DESC".equals(direction))
return o2.compareTo(o1); // 降序
else
return o1.compareTo(o2);
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
}
public static class MapValueComparator implements Comparator<Map.Entry<Double, Integer>> {
private String direction;
public MapValueComparator(String direction) {
this.direction = direction;
}
@Override
public int compare(Map.Entry<Double, Integer> o1, Map.Entry<Double, Integer> o2) {
if ("DESC".equals(direction))
return o2.getValue().compareTo(o1.getValue()); // 降序
else
return o1.getValue().compareTo(o2.getValue());
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
}
public static void main(String args[]) {
Map<Double, Integer> map = new HashMap<>();
map.put(100.21, 10);
map.put(120.21, 20);
map.put(104.21, 30);
map.put(99.32, 70);
map.put(114.22, 45);
TreeMap<Double, Integer> newMap = sortMapByKey(map, "DESC");
System.out.println("after sortByKey:");
for (Map.Entry<Double, Integer> entry : newMap.entrySet()) {
System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
}
System.out.println("lastKey:" + newMap.lastKey());
System.out.println("lastEntry:" + newMap.lastEntry().getValue());
Map<Double, Integer> valueMap = sortMapByValue(map, "DESC");
System.out.println("---------------------------");
System.out.println("after sortByValue:");
for (Map.Entry<Double, Integer> entry : valueMap.entrySet()) {
System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
}
System.out.println("firstKey:" + valueMap.entrySet().iterator().next().getKey());
System.out.println("firstValue:" + valueMap.entrySet().iterator().next().getValue());
}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed 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 com.luqj.util;
import java.util.List;
import java.util.Map;
/**
* Extension of the {@code Map} interface that stores multiple values.
*
* @author Arjen Poutsma
* @since 3.0
*/
public interface MultiValueMap<K, V> extends Map<K, List<V>> {
/**
* Return the first value for the given key.
* @param key the key
* @return the first value for the specified key, or <code>null</code>
*/
V getFirst(K key);
/**
* Add the given single value to the current list of values for the given key.
* @param key the key
* @param value the value to be added
*/
void add(K key, V value);
/**
* Set the given single value under the given key.
* @param key the key
* @param value the value to set
*/
void set(K key, V value);
/**
* Set the given values under.
* @param values the values.
*/
void setAll(Map<K, V> values);
/**
* Returns the first values contained in this {@code MultiValueMap}.
* @return a single value representation of this map
*/
Map<K, V> toSingleValueMap();
}
@@ -0,0 +1,460 @@
package com.luqj.util;
import com.luqj.util.assertion.Assert;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DecimalFormat;
public abstract class NumFormat {
/**
* 设置double类型的精确度
* @param scale 小数点后保留的位数
* @param number 要精确度的值
* @return
*/
public static double setScale(double number,int scale){
if(Double.isNaN(number)){
return 0;
}
if(Double.isInfinite(number)){
return 0;
}
return new BigDecimal(number).setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 将NUMBER转换成String如果value为Null则返回空字符串
* @param value
* @return
* @author:lwei
*/
public static String toString(Number value){
return value == null ? "" : value.toString();
}
/**
* 将Date转换成Long
* @param value
* @return
*/
public static long $Date(Object value) {
if(value == null){
return 0;
}
if(value instanceof Date) {
return ((Date) value).getTime();
}
return $Long(value.toString());
}
/**
* 将Timestamp转换成Long
* @param value
* @return
*/
public static long $Timestamp(Object value) {
if(value == null){
return 0;
}
if(value instanceof Timestamp) {
return ((Timestamp) value).getTime();
}
return $Long(value.toString());
}
/**
* 将类型转换为LONG
* @param value
* @return
*/
public static long $Long(Long value){
return value != null ? value.longValue() : 0;
}
/**
* 将类型转换为LONG
* @param value
* @return
*/
public static long $Long(String value){
return Validator.hasText(value) ? Long.valueOf(value.trim()) : 0;
}
/**
* 将类型转换为LONG
* @param value
* @return
*/
public static long $Long(Object value){
if(value == null){
return 0;
}
if(value instanceof Long) {
return (Long)value;
}
return $Long(value.toString());
}
public static long $Long(BigDecimal value){
return value != null ? value.longValue() : 0;
}
public static long $Long(BigInteger value){
return value != null ? value.longValue() : 0;
}
public static long $Long(Double value){
return value != null ? value.longValue() : 0;
}
public static int $Intger(Integer value){
return value != null ? value.intValue() : 0;
}
public static int $Intger(Double value){
return value != null ? value.intValue() : 0;
}
public static int $Intger(String value){
return Validator.hasText(value) ? Integer.valueOf(value.trim()) : 0;
}
public static int $Intger(Object value){
if(value == null){
return 0;
}
if(value instanceof Integer) {
return (Integer)value;
}
return $Intger(value.toString());
}
public static int $Intger(BigDecimal value){
return value != null ? value.intValue() : 0;
}
public static int $Intger(BigInteger value){
return value != null ? value.intValue() : 0;
}
public static double $Double(Double value){
return value != null ? value.doubleValue() : 0;
}
public static double $Double(String value){
return Validator.hasText(value) ? Double.valueOf(value.trim()) : 0;
}
public static double $Double(BigDecimal value){
return value != null ? value.doubleValue() : 0;
}
public static double $Double(BigInteger value){
return value != null ? value.doubleValue() : 0;
}
public static double $Double(Object value){
if(value == null){
return 0;
}
if(value instanceof Double) {
return (Double)value;
}
return $Double(value.toString());
}
public static float $Float(Float value){
return value != null ? value.floatValue() : 0;
}
public static double $Float(String value){
return Validator.hasText(value) ? Float.valueOf(value.trim()) : 0;
}
public static double $Float(BigDecimal value){
return value != null ? value.floatValue() : 0;
}
public static double $Float(BigInteger value){
return value != null ? value.floatValue() : 0;
}
public static double $Float(Object value){
if(value == null){
return 0;
}
if(value instanceof Float) {
return (Float)value;
}
return $Float(value.toString());
}
public static short $Short(Short value){
return value != null ? value.shortValue() : 0;
}
public static short $Short(String value){
return Validator.hasText(value) ? Short.valueOf(value.trim()) : 0;
}
public static short $Short(BigDecimal value){
return value != null ? value.shortValue() : 0;
}
public static short $Short(BigInteger value){
return value != null ? value.shortValue() : 0;
}
public static short $Short(Object value){
if(value == null){
return 0;
}
if(value instanceof Short) {
return (Short)value;
}
return $Short(value.toString());
}
public static byte $Byte(Byte value){
return value != null ? value.byteValue() : 0;
}
public static byte $Byte(BigDecimal value){
return value != null ? value.byteValue() : 0;
}
public static byte $Byte(BigInteger value){
return value != null ? value.byteValue() : 0;
}
public static byte $Byte(String value){
return Validator.hasText(value) ? Byte.valueOf(value.trim()) : 0;
}
public static byte $Byte(Object value){
return Validator.notNull(value) ? $Byte(value.toString()) : 0;
}
/**
* 将指定的<code>Number</code>对象转换为指定的类型对象
*
* @param number the number to convert
* @return 目标类型的对象
*/
public static Number convertNumber(Number number, Class targetClass)
throws IllegalArgumentException {
Assert.notNull(number, "Number对象不可以为null");
Assert.notNull(targetClass, "Number目标类对象参数不可以为null");
if (targetClass.isInstance(number)) {
return number;
}else if (targetClass.equals(Byte.class)) {
long value = number.longValue();
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return new Byte(number.byteValue());
}else if (targetClass.equals(Short.class)) {
long value = number.longValue();
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return new Short(number.shortValue());
}else if (targetClass.equals(Integer.class)) {
long value = number.longValue();
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return new Integer(number.intValue());
}else if (targetClass.equals(Long.class)) {
return new Long(number.longValue());
}else if (targetClass.equals(Float.class)) {
return new Float(number.floatValue());
}else if (targetClass.equals(Double.class)) {
return new Double(number.doubleValue());
}else if (targetClass.equals(BigInteger.class)) {
return BigInteger.valueOf(number.longValue());
}else if (targetClass.equals(BigDecimal.class)) {
// using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
// (see BigDecimal javadoc for details)
return new BigDecimal(number.toString());
}else {
throw new IllegalArgumentException("无法将值为 [" + number + "] 类型为 [" +
number.getClass().getName() + "] 的对象转换为 [" + targetClass.getName() + "]");
}
}
/**
* 如果指定的值超过了指定的类型的值所能容纳的最大或最小值将抛该异常
* @param number 需要转换的值
* @param targetClass 目标对象的类型
*/
private static void raiseOverflowException(Number number, Class targetClass) {
throw new IllegalArgumentException("无法将值为 [" + number + "] 类型为 [" +
number.getClass().getName() + "] 的对象转换为 [" + targetClass.getName() + "]: 值超过了目标对象的值得范围");
}
/**
* 将字符串格式转换为指定的目标类的Number对象
* @param text 需要转换的字符串
* @param targetClass 目标类型
* @return 目标类型的对象
* @throws IllegalArgumentException 如果不支持指定的目标类型的话将抛该异常
*/
public static Number parseNumber(String text,Class targetClass) {
Assert.notNull(text, "字符串参数不可以为null");
Assert.notNull(targetClass, "Number目标类对象参数不可以为null");
String trimmed = text.trim();
if (targetClass.equals(Byte.class)) {
return Byte.decode(trimmed);
}
else if (targetClass.equals(Short.class)) {
return Short.decode(trimmed);
}
else if (targetClass.equals(Integer.class)) {
return Integer.decode(trimmed);
}
else if (targetClass.equals(Long.class)) {
return Long.decode(trimmed);
}
else if (targetClass.equals(Float.class)) {
return Float.valueOf(trimmed);
}
else if (targetClass.equals(Double.class)) {
return Double.valueOf(trimmed);
}
else if (targetClass.equals(BigInteger.class)) {
return decodeBigInteger(trimmed);
}
else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
return new BigDecimal(trimmed);
}
else {
throw new IllegalArgumentException(
"转换失败! String [" + text + "] to target class [" + targetClass.getName() + "]");
}
}
/**
* 将字符串转换为<code>BigInteger</code>
*
* <p>指定的字符串如果是可以是负数表示或者十六进制,八进制表示
* 负数表示前面加-,十六进制表示前面加0x 0X #,八进制表示前面加0<p>
* @param value 要转换的字符串
* @return 返回<code>BigInteger</code>对象
* @see BigInteger#BigInteger(String, int)
*/
private static BigInteger decodeBigInteger(String value) {
int radix = 10;//基数
int index = 0;//串索引
boolean negative = false;//判断是否为负数
if (value.startsWith("-")) {
negative = true;
index++;
}
if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (value.startsWith("#", index)) {
index++;
radix = 16;
}
else if (value.startsWith("0", index) && value.length() > 1 + index) {
index++;
radix = 8;
}
BigInteger result = new BigInteger(value.substring(index), radix);
return (negative ? result.negate() : result);
}
/**
*
* @param number
* @return
*/
public static String setString(double number){
return number==0?"&nbsp;&nbsp;":String.valueOf(number);
}
/**
* 两个Double类型相加后返回Double类型(如果其中一个为NULL则视为0)
* @param value1
* @param value2
* @return
*/
public static Double addValue(Double value1,Double value2){
return $Double(value1)+$Double(value2);
}
/**
* 两个Long类型相加后返回Long类型(如果其中一个为NULL则视为0)
* @param value1
* @param value2
* @return
*/
public static Long addValue(Long value1,Long value2){
return $Long(value1)+$Long(value2);
}
/**
* 将double类型的数据改为非科学记数法表示
* @param unFormatedNumber
* @return
*/
public static String formateNonScience(double unFormatedNumber){
DecimalFormat format = new DecimalFormat("#0.000");
return format.format(unFormatedNumber);
}
public static Number parseNum(Class targetClass,Number v){
if(targetClass.equals(Byte.class)){
return Byte.valueOf(v.byteValue());
}
else if (targetClass.equals(Short.class)) {
return Short.valueOf(v.shortValue());
}
else if (targetClass.equals(Integer.class)) {
return Integer.valueOf(v.intValue());
}
else if (targetClass.equals(Long.class)) {
return Long.valueOf(v.longValue());
}
else if (targetClass.equals(Float.class)) {
return Float.valueOf(0);
}
else if (targetClass.equals(Double.class)) {
return Double.valueOf(v.doubleValue());
}
else if (targetClass.equals(BigInteger.class)) {
return new BigInteger(String.valueOf(v.longValue()));
}
else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
return new BigDecimal(v.doubleValue());
}
else {
throw new IllegalArgumentException(
"类型[" + targetClass.getName() + "],无法初始化0值");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,248 @@
/**
* 版权所有:厦门市巨龙软件工程有限公司
* Copyright 2010 Xiamen Dragon Software Eng. Co. Ltd.
* All right reserved.
*====================================================
* 文件名称: Assert.java
* 修订记录:
* No 日期 作者(操作:具体内容)
* 1. 2010-8-6 李炜(创建:创建文件)
*====================================================
* 类描述:(说明未实现或其它不应生成javadoc的内容)
*
*/
package com.luqj.util;
import java.util.Collection;
import java.util.Map;
/**
*<pre><b><font color="blue">Assert</font></b></pre>
*
*<pre><b>&nbsp;--描述说明--</b></pre>
* <pre></pre>
* <pre>
* <b>--样例--</b>
* Assert obj = new Assert();
* obj.method();
* </pre>
* JDK版本:JDK1.4
* @author <b>李炜</b>
*/
public abstract class Validator {
/**
* 判断表达式是否为true
* @param expression 要判断的表达式
*/
public static boolean isTrue(boolean expression) {
return expression;
}
/**
* 判断表达式是否为0
* @param expression 要判断的表达式
*/
public static boolean isZero(int num) {
return num == 0;
}
/**
* 判断表达式是否为非空
* @param expression 要判断的表达式
*/
public static boolean notZero(int num, String message) {
return num == 0;
}
/**
* 判断表达式是否为空
* @param expression 要判断的表达式
*/
public static boolean isNull(Object object) {
return object == null;
}
/**
* 判断表达式是否为非空
* @param expression 要判断的表达式
*/
public static boolean notNull(Object object) {
return object != null;
}
/**
* 判断字符串长度是否大于指定长度
* @param text 字符串
* @param size 指定长度
*/
public static boolean gtLength(String text,int size){
return notNull(text) && text.length() > size;
}
public static boolean gtLength(Collection collection,int size){
return notNull(collection) && collection.size() > size;
}
public static boolean gtLength(Map collection,int size){
return notNull(collection) && collection.size() > size;
}
/**
* 判断字符串长度是否小于指定长度
* @param text 字符串
* @param size 指定长度
*/
public static boolean ltLength(String text,int size){
return notNull(text) && text.length() < size;
}
public static boolean ltLength(Collection collection,int size){
return notNull(collection) && collection.size()< size;
}
public static boolean ltLength(Map collection,int size){
return notNull(collection) && collection.size()< size;
}
/**
* 判断text是否为有内容字符串
* @param text 要判断的字符串
*/
public static boolean hasLength(String text) {
return notNull(text) && gtLength(text, 0);
}
public static boolean hasLength(Object[] arrays){
return notNull(arrays) && arrays.length > 0;
}
/**
* 判断text是否为有内容字符串
* @param text 要判断的字符串
*/
public static boolean hasLength(StringBuffer text) {
return notNull(text) && gtLength(text.toString(), 0);
}
/**
* 判断text是否为有内容,如果都是空白字符也将抛异常
* @param text 要判断的字符串
*/
public static boolean hasText(String text) {
return notNull(text) && gtLength(text.trim(), 0);
}
public static boolean hasText(StringBuffer sb){
return notNull(sb) && gtLength(sb.toString().trim(), 0);
}
/**
* 判断数组是否大于指定长度
* @param array 数组
* @param size 长度
*/
public static boolean gtSize(Object[] array,int size){
return notNull(array) && array.length > size;
}
/**
* 判断数组是否小于指定长度
* @param array 数组
* @param size 长度
*/
public static boolean ltSize(Object[] array,int size){
return notNull(array) && array.length < size;
}
/**
* 判断数组是否为空数组
* @param array 要判断的数租
*/
public static boolean notEmpty(Object[] array) {
return notNull(array) && gtSize(array, 0);
}
/**
* 判断集合是否为空集合对象
* @param array 要判断的集合对象
*/
public static boolean notEmpty(Collection collection) {
return notNull(collection) && !collection.isEmpty();
}
/**
* 判断Map是否为空对象,有默认消息
* @param array 要判断的Map
* @throws IllegalArgumentException 如果是空集合对象或者null
*/
public static boolean notEmpty(Map map) {
return notNull(map) && !map.isEmpty();
}
/**
*判断指定的 Object 是否与此 type 所表示的对象赋值兼容
* @param 用于检查的Class对象
* @param obj 用于检查的对象
*/
public static boolean isInstanceOf(Class type, Object obj, String message) {
return notNull(type) && type.isInstance(obj);
}
/**
* 判断两个类型是否相同
* @param type1
* @param type2
*/
public static boolean isSameType(Class type1,Class type2,String message){
return notNull(type1) && notNull(type2) && type1.equals(type2);
}
/**
* 判断一个class对象调用newInstance,是否成功
* @param type
*/
public static boolean isNewInstanceOf(Class type){
if(notNull(type)){
try {
type.newInstance();
return true;
} catch (Exception e) {
return false;
}
}else{
return false;
}
}
/**
* 判断superType.isAssignableFrom(subType)是否为true
* @param superType 超类
* @param subType 子类
*/
public static boolean isAssignable(Class superType, Class subType) {
return notNull(superType) && notNull(subType) && superType.isAssignableFrom(subType);
}
}
@@ -0,0 +1,395 @@
/**
* 版权所有:厦门市巨龙软件工程有限公司
* Copyright 2010 Xiamen Dragon Software Eng. Co. Ltd.
* All right reserved.
*====================================================
* 文件名称: Assert.java
* 修订记录:
* No 日期 作者(操作:具体内容)
* 1. 2010-8-6 李炜(创建:创建文件)
*====================================================
* 类描述:(说明未实现或其它不应生成javadoc的内容)
*
*/
package com.luqj.util.assertion;
import com.luqj.util.log.LogUtil;
import java.util.Collection;
import java.util.Map;
/**
*<pre><b><font color="blue">Assert</font></b></pre>
*
*<pre><b>&nbsp;--描述说明--</b></pre>
* <pre></pre>
* <pre>
* <b>--样例--</b>
* Assert obj = new Assert();
* obj.method();
* </pre>
* JDK版本:JDK1.4
* @author <b>李炜</b>
*/
public abstract class Assert {
/**
* 断言表达式是否为true
* @param expression 要断言的表达式
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不是true
*/
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言表达式是否为true,有默认消息
* @param expression 要断言的表达式
* @throws IllegalArgumentException 如果不是true
*/
public static void isTrue(boolean expression) {
isTrue(expression, "[断言失败] - 参数必须是 true");
}
/**
* 断言表达式是否为0
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不是空
*/
public static void isZero(long num, String message) {
if (num != 0) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言表达式是否为空,有默认消息
* @throws IllegalArgumentException 如果不是空
*/
public static void isZero(long num) {
isZero(num, "[断言失败] - 参数值必须是0");
}
/**
* 断言表达式是否为非空
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不是非空
*/
public static void notZero(long num, String message) {
if (num == 0) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言表达式是否为非空,有默认消息
* @throws IllegalArgumentException 如果不是非空
*/
public static void notZero(long num) {
notZero(num, "[断言失败] - 参数必须非0");
}
/**
* 断言表达式是否为空
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不是空
*/
public static void isNull(Object object, String message) {
if (object != null) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言表达式是否为空,有默认消息
* @throws IllegalArgumentException 如果不是空
*/
public static void isNull(Object object) {
isNull(object, "[断言失败] - 参数必须是 null");
}
/**
* 断言表达式是否为非空
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不是非空
*/
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言表达式是否为非空,有默认消息
* @throws IllegalArgumentException 如果不是非空
*/
public static void notNull(Object object) {
notNull(object, "[断言失败] - 参数必须是非空对象");
}
/**
* 断言表达式是否为非空,有默认消息
* @throws IllegalArgumentException 如果不是非空
*/
public static void notNull(Object... objects) {
for (int i = 0; i < objects.length; i++) {
notNull(objects[i], "[断言失败] - 参数["+i+"]必须是非空对象");
}
}
/**
* 断言text是否为有内容字符串
* @param text 要断言的字符串
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果是空串或null对象
*/
public static void hasLength(String text, String message) {
if (text == null || text.length() == 0) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言text是否为有内容字符串,有默认消息
* @param text 要断言的字符串
* @throws IllegalArgumentException 如果是空串或null对象
*/
public static void hasLength(String text) {
hasLength(text,
"[断言失败] - 参数必须是非空字符串");
}
/**
* 断言text是否为有内容,如果都是空白字符也将抛异常
* @param text 要断言的字符串
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果是空串或null对象,或所有内容为空白字符
*/
public static void hasText(String text, String message) {
if (text == null || text.trim().length() == 0) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言text是否为有内容,如果都是空白字符也将抛异常,有默认消息
* @param text 要断言的字符串
* @throws IllegalArgumentException 如果是空串或null对象,或所有内容为空白字符
*/
public static void hasText(String text) {
hasText(text,
"[断言失败] - text必须是有内容的,有内容指不是全部为空白字符的字符串");
}
/**
* 断言数组是否为空数组
* @param array 要断言的数租
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果是空数组或者null
*/
public static void notEmpty(Object[] array, String message) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言数组是否为空数组,有默认消息
* @param array 要断言的数租
* @throws IllegalArgumentException 如果是空数组或者null
*/
public static void notEmpty(Object[] array) {
notEmpty(array, "[断言失败] - 参数数组必须是非空数组");
}
/**
* 断言集合是否为空集合对象
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果是空集合对象或者null
*/
public static void notEmpty(Collection collection, String message) {
if (collection == null || collection.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言集合是否为空集合对象,有默认消息
* @throws IllegalArgumentException 如果是空集合对象或者null
*/
public static void notEmpty(Collection collection) {
notEmpty(collection,
"[断言失败] - 集合参数必须是有内容的");
}
/**
* 断言Map是否为空对象
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果是空集合对象或者null
*/
public static void notEmpty(Map map, String message) {
if (map == null || map.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/**
* 断言Map是否为空对象,有默认消息
* @throws IllegalArgumentException 如果是空集合对象或者null
*/
public static void notEmpty(Map map) {
notEmpty(map, "[断言失败] - Map参数必须是有内容的");
}
/**
*断言指定的 Object 是否与此 type 所表示的对象赋值兼容
* @param obj 用于检查的对象
* @throws IllegalArgumentException 如果不兼容
*/
public static void isInstanceOf(Class clazz, Object obj) {
isInstanceOf(clazz, obj, "");
}
/**
*断言指定的 Object 是否与此 type 所表示的对象赋值兼容
* @param obj 用于检查的对象
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不兼容
*/
public static void isInstanceOf(Class type, Object obj, String message) {
notNull(type, "类型对象不可为空");
if (!type.isInstance(obj)) {
throw new IllegalArgumentException(message +
"Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
"] must be an instance of " + type);
}
}
/**
* 断言一个class对象调用newInstance,是否成功
* @param type
* @throws IllegalArgumentException 如果不成功
*/
public static void isNewInstanceOf(Class type){
isNewInstanceOf(type,"");
}
/**
* 断言两个类型是否相同
* @param type1
* @param type2
*/
public static void isSameType(Class type1,Class type2,String message){
notNull(type1,"类型对象不可为空");
notNull(type2,"类型对象不可为空");
if(!type1.equals(type2)){
throw new IllegalArgumentException(message);
}
}
/**
* 断言两个类型是否相同
* @param type1
* @param type2
*/
public static void isSameType(Class type1,Class type2){
isSameType(type1, type2, "必须是相同类型");
}
/**
* 断言一个class对象调用newInstance,是否成功
* @param type
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果不成功
*/
public static void isNewInstanceOf(Class type,String message){
notNull(type,"类型对象不可为空");
try {
type.newInstance();
} catch (InstantiationException e) {
throw new IllegalArgumentException(message +
"Class [" + type +"] must be can new instance ");
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(message +
"Class [" + type +"] must be can new instance ");
}
}
/**
* 断言superType.isAssignableFrom(subType)是否为true
* @param superType 超类
* @param subType 子类
* @throws IllegalArgumentException 如果调用该方法为false
*/
public static void isAssignable(Class superType, Class subType) {
isAssignable(superType, subType, "");
}
/**
* 断言superType.isAssignableFrom(subType)是否为true
* @param superType 超类
* @param subType 子类
* @param message 抛异常以后的消息
* @throws IllegalArgumentException 如果调用该方法为false
*/
public static void isAssignable(Class superType, Class subType, String message) {
notNull(superType, "超类的类对象必须为非空");
if (subType == null || !superType.isAssignableFrom(subType)) {
throw new IllegalArgumentException(message + subType + " is not assignable to " + superType);
}
}
/**
* 断言一个对象所属状态值是否为true
* @param expression 要断言的状态表达式
* @param message 抛异常以后的消息
* @throws IllegalStateException 如果表达式为false
*/
public static void state(boolean expression, String message) {
if (!expression) {
throw new IllegalStateException(message);
}
}
/**
* 断言一个对象所属状态值是否为true,有默认消息
* @param expression 要断言的状态表达式
* @throws IllegalStateException 如果表达式为false
*/
public static void state(boolean expression) {
state(expression, "[断言失败] - 状态表达式必须式true");
}
public static void logic(boolean expression,String message){
if (!expression) {
throw new IllegalLogicException(message);
}
}
public static void logic(boolean expression){
logic(expression, "[断言失败] - 逻辑表达式必须是true");
}
public static void fail(String message){
throw new IllegalLogicException(message);
}
public static void fail(String message,Throwable e){
throw new IllegalLogicException(LogUtil.exceptionMsg(message,e),e);
}
}
@@ -0,0 +1,21 @@
package com.luqj.util.assertion;
public class IllegalLogicException extends RuntimeException {
public IllegalLogicException() {
super();
}
public IllegalLogicException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public IllegalLogicException(String arg0) {
super(arg0);
}
public IllegalLogicException(Throwable arg0) {
super(arg0);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,174 @@
package com.luqj.util.log;
import java.io.PrintWriter;
import java.io.StringWriter;
public abstract class LogUtil {
private static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
t.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
public static String exceptionMsg(String msg, Throwable e) {
return msg + ",异常消息[" + getStackTrace(e) + "]";
}
public static String exceptionSimpleMsg(String msg, Throwable e) {
return msg + ",异常消息[" + e.getLocalizedMessage() + "]";
}
/**
* 获取计算程序运行的时钟
*
* @return clock
*/
public static Clock getClock() {
return new Clock() {
/**开始时间*/
private long startTime = System.nanoTime();
/**
* 消耗时间[毫秒]
* @return 消耗时间
*/
public long consume() {
return LogUtil.consume(startTime, System.nanoTime());
}
/**
* 结束时间
*/
public long getEnd() {
return System.nanoTime();
}
/**
* 开始时间
*/
public long getStart() {
return startTime;
}
public long consumeSecond() {
return LogUtil.consumeSecond(startTime, System.nanoTime());
}
};
}
/**
* 消耗时间[纳秒]
*
* @return 消耗时间 秒
*/
public static long consumeNano(long startTime, long endTime) {
return (endTime - startTime) / 1000000000 + 1;
}
/**
* 消耗时间[微秒]
*
* @return 消耗时间 秒
*/
public static long consume(long startTime, long endTime) {
return (endTime - startTime) / 1000000 + 1;
}
/**
* 消耗时间[耗秒]
*
* @return 消耗时间 秒
*/
public static long consumeSecond(long startTime, long endTime) {
return (endTime - startTime) / 1000 + 1;
}
/**
* getRootCause
* 获取异常的原始异常,用于反馈异常的真实原因。
*
* @param ex 异常信息
* @return 原始异常,最底层异常
* @author 林小松
*/
public static Throwable getRootCause(Throwable ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
}
/**
* 递归寻找根异常异常信息
*
* @param ex 异常
* @return 异常信息
*/
public static String traceRootExceptionInfo(Throwable ex) {
Throwable cause = ex;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause.toString();
}
/**
* 递归寻找引起异常的所有异常信息
*
* @param ex 异常
* @return 异常信息
*/
public static String tarceExceptionInfo(Throwable ex) {
StringBuffer sb = new StringBuffer();
Throwable cause = ex;
sb.insert(0, cause);
while (cause.getCause() != null) {
cause = cause.getCause();
sb.insert(0, cause.toString());
}
return sb.toString();
}
public static interface Clock {
/**
* 返回程序消耗的毫秒数
*
* @return 消耗毫秒数
*/
long consume();
/**
* 返回程序消耗的秒数
*
* @return 消耗秒数
*/
long consumeSecond();
/**
* 返回开始时间
*
* @return 开始时间
* @author:lwei
*/
long getStart();
/**
* 返回结束时间
*
* @return 结束时间
* @author:lwei
*/
long getEnd();
}
}
@@ -0,0 +1,65 @@
package com.luqj.util.parse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 符号集
* @author chenzm
*/
public class SymbolSet {
/**等号*/
public final static String SYMBOL_EQ = "=";
/**空字符*/
public final static Character SYMBOL_NULL = ' ';
/**逗号*/
public final static String SYMBOL_COMMA = ",";
/**双引号*/
public final static String SYMBOL_DQM = "\"";
/**单引号*/
public final static String SYMBOL_SQM = "\'";
public static String chr2Str(char chr) {
return "" + chr;
}
static boolean isInSymbol(Map<String, List<Integer>> symBolPos, int charPos, String ...symbols){
for(String symbol : symbols) {
if(!symBolPos.containsKey(symbol)) {
return false;
}
List<Integer> posInfo = symBolPos.get(symbol);
for(int i = 0; i < posInfo.size(); ) {
if(charPos > posInfo.get(i) && charPos < posInfo.get(i + 1)) {
return true;
}
i+=2;
}
}
return false;
}
static Map<String, List<Integer>> getSymBolPos(String exp) {
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
String[] symbols = new String[]{
SYMBOL_SQM, SYMBOL_DQM
};
for(String symbol : symbols) {
map.put(symbol, new ArrayList<Integer>(exp.length()));
int charPos = 0;
for(char c : exp.toCharArray()) {
if(c == symbol.charAt(0)) {
map.get(symbol).add(charPos);
}
charPos++;
}
}
return map;
}
}
@@ -0,0 +1,762 @@
package com.luqj.util.reflect;
import com.luqj.util.NumFormat;
import com.luqj.util.assertion.Assert;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtils {
private static Logger LOGGER = LoggerFactory.getLogger(ClassUtils.class);
private static ClassPool pool = ClassPool.getDefault();
static {
}
public static Annotation[] getAnnotation(Class type, Class annotation) {
List<Annotation> list = new ArrayList<Annotation>();
Class<?> clazz = type;
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
if (clazz.getAnnotation(annotation) != null) {
list.add(clazz.getAnnotation(annotation));
}
} catch (Exception e) {
// 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
// 如果这里的异常打印或者往外抛,则就不会执行clazz =
// clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return list.toArray(new Annotation[]{});
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager<Book>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenericity(Class clazz, int index) throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
public static String getDefBeanName(Class<?> classType) {
String name = classType.getSimpleName();
String firstChat = name.substring(0, 1).toLowerCase();
return firstChat + name.subSequence(1, name.length());
}
public static<T> T instanceByConstructor(Class<T> tClass,Object... constructorParams) throws Throwable{
Class[] constructorTypes = new Class[constructorParams.length];
for (int i = 0; i < constructorParams.length; i++) {
constructorTypes[i] = constructorParams[i].getClass();
}
Constructor cla = tClass.getDeclaredConstructor(constructorTypes);
return (T) cla.newInstance(constructorParams);
}
public static String classPackageAsResourcePath(Class<?> clazz) {
if (clazz == null) {
return "";
}
String className = clazz.getName();
int packageEndIndex = className.lastIndexOf('.');
if (packageEndIndex == -1) {
return "";
}
String packageName = className.substring(0, packageEndIndex);
return packageName.replace('.', '/');
}
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system class loader...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassUtils.class.getClassLoader();
}
return cl;
}
public static Map<String, MethodParam> getMethodParams(Class<?> clas, Method m) throws NotFoundException {
Map<String, MethodParam> params = new LinkedHashMap<String, MethodParam>();
pool.insertClassPath(new ClassClassPath(clas));
CtClass ctClass = pool.get(clas.getName());
CtMethod cm = ctClass.getDeclaredMethod(m.getName());
MethodInfo methodInfo = cm.getMethodInfo();
Class<?>[] parameterTypes = m.getParameterTypes();
Type[] parameterGTypes = m.getGenericParameterTypes();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
throw new NotFoundException(codeAttribute.toString());
}
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int j = 0; j < paramNames.length; j++) {
MethodParam mp = new MethodParam(j, attr.variableName(j + pos), parameterTypes[j]);
mp.setT(getTypeGenericity(parameterGTypes[j]));
params.put(mp.getName(), mp);
}
LOGGER.trace("方法[" + m.getName() + "]参数为" + params);
return params;
}
/**
* 获取类型属性的泛型类型
*
* @return
*/
public static Class<?>[] getTypeGenericity(Type fc) {
if (fc == null) {
return new Class<?>[]{};
}
// 【3】如果是泛型参数的类型
if (fc instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) fc;
Type[] ts = pt.getActualTypeArguments();
List<Class<?>> t = new ArrayList<Class<?>>();
for (int i = 0; i < ts.length; i++) {
if (ts[i] instanceof WildcardType) {
//泛型可能是 <?>
} else {
t.add((Class<?>) ts[i]);
}
}
return t.toArray(new Class<?>[]{});
} else {
return new Class<?>[]{};
}
}
public static boolean isListType(Field field) {
return isListType(field.getType());
}
public static boolean isListType(Class<?> objType) {
Class<?>[] interfaces = objType.getInterfaces();
for (Class<?> i : interfaces) {
if (i.equals(List.class)) {
return true;
}
}
return objType.isAssignableFrom(List.class);
}
public static boolean isMapType(Field field) {
Class<?> fieldClazz = field.getType();
return isMapType(fieldClazz);
}
public static boolean isMapType(Class<?> objType) {
return isType(objType, Map.class);
}
public static boolean isSetType(Field field) {
Class<?> fieldClazz = field.getType();
return isSetType(fieldClazz);
}
public static boolean isSetType(Class<?> objType) {
return isType(objType, Set.class);
}
/**
* @return
*/
public static boolean isType(Class<?> parentType, Class<?> child) {
return parentType.isAssignableFrom(child);
}
/**
* 获取List类型属性的泛型类型
*
* @param field
* @return
*/
public static Type getSetFieldGenericity(Field field) {
Class<?> fieldClazz = field.getType();
Assert.logic(isSetType(fieldClazz), "属性类型必须为Set类型");
Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型
if (fc == null) {
return null;
}
// 【3】如果是泛型参数的类型
if (fc instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) fc;
return pt.getActualTypeArguments()[0]; // 【4】
} else {
return null;
}
}
/**
* 获取List类型属性的泛型类型
*
* @param field
* @return
*/
public static Type[] getMapFieldGenericity(Field field) {
Class<?> fieldClazz = field.getType();
Assert.logic(isMapType(fieldClazz), "属性类型必须为Map类型");
Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型
if (fc == null) {
return null;
}
// 【3】如果是泛型参数的类型
if (fc instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) fc;
return pt.getActualTypeArguments(); // 【4】
} else {
return null;
}
}
/**
* 获取List类型属性的泛型类型
*
* @param field
* @return
*/
public static Class<?> getListGenericity(Field field) {
Class<?> fieldClazz = field.getType();
Assert.logic(isListType(fieldClazz), "属性类型必须为List类型");
Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型
if (fc == null) {
return null;
}
// 【3】如果是泛型参数的类型
if (fc instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) fc;
return (Class<?>) pt.getActualTypeArguments()[0]; // 【4】
} else {
return null;
}
}
/**
* 获取List类型属性的泛型类型
*
* @param field
* @return
*/
public static Class<?> getListFieldGenericity(Field field) {
Class<?> fieldClazz = field.getType();
Assert.logic(fieldClazz.isAssignableFrom(List.class), "属性类型必须为List类型");
Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型
if (fc == null) {
return null;
}
// 【3】如果是泛型参数的类型
if (fc instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) fc;
return (Class<?>) pt.getActualTypeArguments()[0]; // 【4】
} else {
return null;
}
}
/**
* 判断属性名是否存在避免调用 getField(String name) 抛异常
*
* @param type
* @return
*/
public static boolean existField(Class<?> type, Class<?> fieldType) {
if (fieldType == null) {
return false;
}
Field[] fs = getDeclaredFields(type);
for (Field field : fs) {
if (field.getType().equals(fieldType)) {
return true;
}
}
return false;
}
public static Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
Method method = null;
for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
clazz.getMethods();
method = clazz.getMethod(methodName, parameterTypes);
return method;
} catch (Exception e) {
//这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
//如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return null;
}
public static Method[] getDeclaredMethods(Object object) {
List<Method> list = new ArrayList<Method>();
for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
for (Method method : clazz.getDeclaredMethods()) {
if (!Modifier.isStatic(method.getModifiers())) {
list.add(method);
}
}
} catch (Exception e) {
//这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
//如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return list.toArray(new Method[]{});
}
/**
* 递归获取所有的接口
*
* @param clazz
* @return
*/
public static Class<?>[] getInterfaces(Class<?> clazz) {
List<Class<?>> list = new LinkedList<Class<?>>();
Class<?>[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
Class ifs = interfaces[i];
list.add(ifs);
list.addAll(Arrays.asList(getInterfaces(ifs)));
}
return list.toArray(new Class[list.size()]);
}
/**
* 直接调用对象方法, 而忽略修饰符(private, protected, default)
*
* @param object : 子类对象
* @param methodName : 父类中的方法名
* @param parameterTypes : 父类中的方法参数类型
* @param parameters : 父类中的方法参数
* @return 父类中方法的执行结果
*/
public static Object invokeMethod(Object object, String methodName, Class<?>[] parameterTypes,
Object[] parameters) {
//根据 对象、方法名和对应的方法参数 通过反射 调用上面的方法获取 Method 对象
Method method = getDeclaredMethod(object, methodName, parameterTypes);
Assert.notNull(method, "方法[" + methodName + "]不允许为空");
//抑制Java对方法进行检查,主要是针对私有方法而言
method.setAccessible(true);
try {
if (null != method) {
// 调用object 的 method 所代表的方法,其方法的参数是 parameters
return method.invoke(object, parameters);
}
} catch (Exception e) {
throw new IllegalArgumentException("方法执行异常,异常消息[" + e.getMessage() + "]", e);
}
return null;
}
/**
* 包括父类的属性
*
* @param type
* @return
*/
public static Field[] getDeclaredFields(Class<?> type) {
List<Field> list = new ArrayList<Field>();
Class<?> clazz = type;
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
for (Field field : clazz.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
list.add(field);
}
}
} catch (Exception e) {
// 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
// 如果这里的异常打印或者往外抛,则就不会执行clazz =
// clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return list.toArray(new Field[]{});
}
public static Field[] getDeclaredFields(Class<?> type, Class a) {
List<Field> fs = new ArrayList<>();
Field[] fields = getDeclaredFields(type);
for (Field field : fields) {
if (field.getType().getAnnotation(a) != null) {
fs.add(field);
}
}
return fs.toArray(new Field[]{});
}
/**
* 包括父类的属性
*
* @param type
* @param fieldName
* @return
*/
public static Field getDeclaredFields(Class<?> type, String fieldName) {
Field field = null;
Class<?> clazz = type;
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(fieldName);
return field;
} catch (Exception e) {
// 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
// 如果这里的异常打印或者往外抛,则就不会执行clazz =
// clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return null;
}
/**
* 判断属性名是否存在避免调用 getField(String name) 抛异常
*
* @param type
* @param fieldName
* @return
*/
public static boolean existField(Class<?> type, String fieldName) {
if (fieldName == null) {
return false;
}
return getDeclaredFields(type, fieldName) != null;
}
/**
* 递归寻找属性的类型
*
* @param beanType 根类型
* @param fieldStr 如bean.field.field
* @return
*/
public static final Class<?>[] getTypes(Class<?> beanType, String fieldStr) {
Assert.notNull(beanType, "根类型不允许为空");
Assert.hasText(fieldStr, "属性串不允许为空");
String[] fieldNames = fieldStr.split("\\.");
List<Class<?>> returnTypes = new ArrayList<Class<?>>();
Class<?> returnType = beanType;
for (String fn : fieldNames) {
if (ClassUtils.existField(returnType, fn)) {
Field f;
f = getDeclaredFields(returnType, fn);
returnTypes.add(f.getType());
returnType = f.getType();
} else {
return returnTypes.toArray(new Class<?>[0]);
}
}
return returnTypes.toArray(new Class<?>[0]);
}
public static final boolean isBaseType(Field field) {
Assert.notNull(field, "属性不允许为空!");
return isBaseType(field.getType());
}
public static final Object initBaseValue(Class<?> objType) {
return parseBaseValue(objType, "");
}
public static final Object parseBaseValue(Class<?> objType, Object value) {
Assert.logic(isBaseType(objType), "需要转换的必须是基本类型");
if (Short.class.equals(objType) || short.class.equals(objType)) {
return NumFormat.$Long(value);
} else if (Integer.class.equals(objType) || int.class.equals(objType)) {
return NumFormat.$Intger(value);
} else if (Long.class.equals(objType) || long.class.equals(objType)) {
return NumFormat.$Long(value);
} else if (Float.class.equals(objType) || float.class.equals(objType)) {
return NumFormat.$Float(value);
} else if (Double.class.equals(objType) || double.class.equals(objType)) {
return NumFormat.$Double(value);
} else if (String.class.equals(objType)) {
return value;
} else if (Boolean.class.equals(objType) || boolean.class.equals(objType)) {
if (value == null) {
return Boolean.FALSE;
} else {
return Boolean.getBoolean(value.toString());
}
}
return null;
}
public static final Object parseBaseValue(Class<?> objType, String value) {
Assert.logic(isBaseType(objType), "需要转换的必须是基本类型");
if (Short.class.equals(objType) || short.class.equals(objType)) {
return NumFormat.$Short(value.trim());
} else if (Integer.class.equals(objType) || int.class.equals(objType)) {
return NumFormat.$Intger(value.trim());
} else if (Long.class.equals(objType) || long.class.equals(objType)) {
return NumFormat.$Long(value.trim());
} else if (Float.class.equals(objType) || float.class.equals(objType)) {
return NumFormat.$Float(value.trim());
} else if (Double.class.equals(objType) || double.class.equals(objType)) {
return NumFormat.$Double(value.trim());
} else if (String.class.equals(objType)) {
return value;
} else if (Boolean.class.equals(objType) || boolean.class.equals(objType)) {
return Boolean.parseBoolean(value.trim());
}
return null;
}
public static final boolean isBaseType(Class<?> beanType) {
Assert.notNull(beanType, "类型不允许为空!");
return beanType.isPrimitive()
|| String.class.equals(beanType)
|| Long.class.equals(beanType)
|| Short.class.equals(beanType)
|| Character.class.equals(beanType)
|| Integer.class.equals(beanType)
|| Double.class.equals(beanType)
|| Boolean.class.equals(beanType)
|| Float.class.equals(beanType);
}
public static final Object newInstance(Class<?> beanType, String fieldStr)
throws InstantiationException,
IllegalAccessException, SecurityException, NoSuchFieldException {
Assert.notNull(beanType, "根类型不允许为空");
Assert.hasText(fieldStr, "属性串不允许为空");
Class<?>[] types = getTypes(beanType, fieldStr);
if (types.length == 0) {
return null;
}
String[] fieldNames = fieldStr.split("\\.");
Object root = beanType.newInstance();
Object obj = root;
Class<?> tmpType = beanType;
int i = 0;
for (Class<?> type : types) {
Object objTmp = type.newInstance();
GSetterUtil.setValueBySetter(obj, tmpType.getDeclaredField(fieldNames[i]), objTmp);
obj = objTmp;
tmpType = type;
i++;
}
return GSetterUtil.getValueByGetter(root, beanType.getDeclaredField(fieldNames[0]));
}
/**
* 递归寻找属性的类型
*
* @param beanType 根类型
* @param fieldStr 如bean.field.field
* @return
*/
public static final Class<?> getType(Class<?> beanType, String fieldStr) {
Assert.notNull(beanType, "根类型不允许为空");
Assert.hasText(fieldStr, "属性串不允许为空");
String[] fieldNames = fieldStr.split("\\.");
Class<?> returnType = beanType;
for (String fn : fieldNames) {
if (ClassUtils.existField(returnType, fn)) {
Field f;
try {
f = getDeclaredFields(returnType, fn);
returnType = f.getType();
} catch (NullPointerException e) {
//找不到字段返回NULL
return null;
}
} else {
return null;
}
}
return returnType;
}
/**
* 获取某个包下面的class
*
* @param pack
* @return
*/
public static List<String> getClasssFromPackage(String pack) {
List<String> classNames = new ArrayList<String>();
// 是否循环搜索子包
boolean recursive = true;
// 包名字
String packageName = pack;
// 包名对应的路径名称
String packageDirName = packageName.replace('.', '/');
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
System.out.println("file类型的扫描");
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
findClassInPackageByFile(packageName, filePath, recursive, classNames);
} else if ("jar".equals(protocol)) {
System.out.println("jar类型的扫描");
}
}
} catch (Exception e) {
}
return classNames;
}
private static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive, List<String> clazzNames) {
File dir = new File(filePath);
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 在给定的目录下找到所有的文件,并且进行条件过滤
File[] dirFiles = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
boolean acceptDir = recursive && file.isDirectory();// 接受dir目录
boolean acceptClass = file.getName().endsWith("class");// 接受class文件
return acceptDir || acceptClass;
}
});
for (File file : dirFiles) {
if (file.isDirectory()) {
findClassInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, clazzNames);
} else {
String className = file.getName().substring(0, file.getName().length() - 6);
try {
clazzNames.add(packageName + "." + className);
} catch (Exception e) {
}
}
}
}
/**
* 从jar文件中读取指定目录下面的所有的class文件
*
* @param jarPath jar文件存放的位置
* @param jarPath 指定的文件目录
* @return 所有的的class的对象
*/
public static List<String> getClasssFromJarFile(String jarPath) {
List<String> classNameList = new ArrayList<>();
JarFile jarFile = null;
try {
jarFile = new JarFile(jarPath);
} catch (IOException e1) {
}
List<JarEntry> jarEntryList = new ArrayList<>();
Enumeration<JarEntry> ee = jarFile.entries();
while (ee.hasMoreElements()) {
JarEntry entry = ee.nextElement();
// entry.getName().startsWith(filePath) &&
if (entry.getName().endsWith(".class")) {
jarEntryList.add(entry);
}
}
for (JarEntry entry : jarEntryList) {
String className = entry.getName().replace('/', '.');
className = className.substring(0, className.length() - 6);
classNameList.add(className);
}
return classNameList;
}
public static Class[] getMethodParamTypes(Object classInstance, String methodName) {
Class[] paramTypes = null;
try {
Method[] methods = classInstance.getClass().getMethods();//全部方法
for (int i = 0; i < methods.length; i++) {
if (methodName.equals(methods[i].getName())) {//和传入方法名匹配
Class[] params = methods[i].getParameterTypes();
paramTypes = new Class[params.length];
for (int j = 0; j < params.length; j++) {
paramTypes[j] = Class.forName(params[j].getName());
}
break;
}
}
}catch (Throwable e) {
throw new IllegalStateException("获取方法参数类型失败", e);
}
return paramTypes;
}
public static Method findDeclaredMethod(Object object, String methodName) {
Method execMethod = null;
for (Method method : object.getClass().getDeclaredMethods()) {
if (method.getName().equals(methodName)) {
execMethod = method;
break;
}
}
return execMethod;
}
public static void main(String[] args) {
System.out.println(Arrays.asList(getDeclaredFields(ClassUtils.class)));
}
}
@@ -0,0 +1,196 @@
package com.luqj.util.reflect;
import com.luqj.util.assertion.Assert;
import com.luqj.util.log.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public abstract class GSetterUtil {
private static Logger _log = LoggerFactory.getLogger(GSetterUtil.class);
public static final String PREFIX_GETTER = "get";
public static final String PREFIX_SETTER = "set";
public static Object getValueByGetter(Object obj,String fieldName){
Field f = ClassUtils.getDeclaredFields(obj.getClass(), fieldName);
Assert.notNull(f, obj.getClass()+",找不到指定的属性["+fieldName+"]");
return getValueByGetter(obj, f);
}
/**
* 判断属性是否可操作,是否有公共getter,setter方法
* @return
*/
public static boolean isOpAbleField(Class<?> type,Field f){
return getGetter(type, f) != null && getSetter(type, f) != null;
}
/**
* 判断指定的对象属性是否存在getter方法
* @param f
* @return
*/
public static boolean existGetter(Class<?> type,Field f){
return getGetter(type, f) != null;
}
/**
* 判断指定的对象属性是否存在setter方法
* @param f
* @return
*/
public static boolean existSetter(Class<?> type,Field f){
return getSetter(type, f) != null;
}
public static void setValueBySetter(Object obj,Field f,Object paramValue){
setValueBySetter(obj, f.getName(), paramValue,f.getType());
}
public static void setValueBySetter(Object obj,String fieldName,Object paramValue,Class<?> paramType){
Method m = getSetter(obj.getClass(),fieldName,paramType);
Assert.notNull(m,obj.getClass().getSimpleName()+"属性["+fieldName+"]不存在setter方法");
try {
m.invoke(obj,paramValue);
} catch (Throwable e) {
_log.error(LogUtil.exceptionMsg("["+fieldName+"]set方法"+m.getName()+"设置出现异常", e),e);
}
}
public static Object getValueByGetter(Object obj,Field f){
Method m = getGetter(obj.getClass(), f);
Assert.notNull(m,"属性["+f.getName()+"]不存在getter方法");
try {
return m.invoke(obj);
} catch (Throwable e) {
_log.error(LogUtil.exceptionMsg(f+"set方法"+m.getName()+"设置出现异常", e));
return null;
}
}
public static String getGetterMethodName(String fieldName){
Assert.hasText(fieldName,"属性名必须有内容!");
return PREFIX_GETTER + upperFirstChar(fieldName);
}
public static String getSetterMethodName(String fieldName){
Assert.hasText(fieldName,"属性名必须有内容!");
return PREFIX_SETTER + upperFirstChar(fieldName);
}
public static String upperFirstChar(String fieldName){
return fieldName.substring(0,1).toUpperCase()
+ fieldName.substring(1,fieldName.length());
}
public static String lowerFirstChar(String fieldName){
return fieldName.substring(0,1).toLowerCase()
+ fieldName.substring(1,fieldName.length());
}
public static boolean isGetter(Method method){
return method.getModifiers() == Modifier.PUBLIC
&& method.getName().length() > PREFIX_GETTER.length()
&& method.getName().startsWith(PREFIX_GETTER)
&& method.getParameterTypes().length == 0;
}
public static boolean isSetter(Method method){
return (method.getModifiers() & Modifier.PUBLIC) == 1
&& method.getName().length() > PREFIX_SETTER.length()
&& method.getName().startsWith(PREFIX_SETTER)
&& method.getParameterTypes().length == 1;
}
/**
* 获取setter方法,如果找不到或达不到要求返回NULL
* @param type
* @param f
* @return
*/
public static Method getSetter(Class<?> type,String fieldName,Class<?> fieldType){
try {
Method m = type.getMethod(getSetterMethodName(fieldName), fieldType);
if(isSetter(m)){
return m;
}else{
return null;
}
} catch (Exception e) {
return null;
}
}
/**
* 获取setter方法,如果找不到或达不到要求返回NULL
* @param type
* @param f
* @return
*/
public static Method getSetter(Class<?> type,Field f){
return getSetter(type, f.getName(), f.getType());
}
/**
* 获取getter方法,如果找不到或达不到要求返回NULL
* @param type
* @param f
* @return
*/
public static Method getGetter(Class<?> type,Field f){
try {
Method m = type.getMethod(getGetterMethodName(f.getName()));
if(isGetter(m)){
return m;
}else{
return null;
}
} catch (Exception e) {
return null;
}
}
/**
* 根据setter方法获取属性名
* @param method
* @return
*/
public static String getFieldNameBySetter(Method method){
//get开头且没有参数
Assert.notNull(method,"方法不允许为NULL");
Assert.logic(isSetter(method),
method.getName()+"["+method.getParameterTypes().length+"]不是JAVA标准set方法");
String fieldName = method.getName().substring(PREFIX_SETTER.length());
fieldName = lowerFirstChar(fieldName);
return fieldName;
}
/**
* 根据getter方法获取属性名
* @param method
* @return
*/
public static String getFieldNameByGetter(Method method){
//get开头且没有参数
Assert.notNull(method,"方法不允许为NULL");
Assert.logic(isGetter(method),
method.getName()+"["+method.getParameterTypes().length+"]不是JAVA标准get方法");
String fieldName = method.getName().substring(PREFIX_GETTER.length());
fieldName = lowerFirstChar(fieldName);
return fieldName;
}
}
@@ -0,0 +1,139 @@
package com.luqj.util.reflect;
import com.luqj.util.assertion.Assert;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class JarUtils {
public static interface JarOperator {
void operate(JarFile jar, String className, JarEntry entry);
}
public static class ClassLoaderOP implements JarOperator {
private ClassLoader loader;
private Method md1;
public ClassLoaderOP(ClassLoader loader) {
super();
try {
this.loader = loader;
md1 = ClassLoader.class.getDeclaredMethod(
"defineClass",
String.class, byte[].class, int.class, int.class);
md1.setAccessible(true);
} catch (Exception e) {
Assert.fail("jar文件加载初始化异常,异常消息[" + e.getMessage() + "]");
}
}
@Override
public void operate(JarFile jar, String className, JarEntry entry) {
try {
InputStream is = jar.getInputStream(entry);
ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
byte[] packData = new byte[2048];
int readLen = 0;
while (-1 != (readLen = is.read(packData))) {
dataOut.write(packData, 0, readLen);
}
if (dataOut.size() <= 0) {
throw new ClassNotFoundException(className);
}
byte[] classFile = dataOut.toByteArray();
md1.invoke(loader, className, classFile, 0, classFile.length);
} catch (Exception e) {
Assert.fail("类:" + className + "加载异常,异常消息[" + e.getMessage() + "]");
}
}
}
public static void operateJar(String file, JarOperator op) {
try {
JarFile jar = new JarFile(file);
Enumeration<JarEntry> d = jar.entries();
while (d.hasMoreElements()) {
JarEntry entry = (JarEntry) d.nextElement();
if (entry.getName().endsWith(".class")) {
String name = entry.getName();
name = name.substring(0, name.length() - 6);
name = name.replaceAll("/", ".");
op.operate(jar, name, entry);
}
}
} catch (IOException e) {
Assert.fail("解析JAR:" + file + "出现异常,异常消息[" + e.getMessage() + "]");
}
}
public static void loadClass(String file, ClassLoader loader) {
ClassLoaderOP op = new ClassLoaderOP(loader);
operateJar(file, op);
}
/**
* 获取所有的 JAVA类信息
*
* @param file
* @return 返回全局类名
*/
public static Collection<String> getAllClassInfo(String file) {
List<String> infos = new ArrayList<String>();
try {
JarFile jar = new JarFile(file);
Enumeration<JarEntry> d = jar.entries();
while (d.hasMoreElements()) {
JarEntry entry = (JarEntry) d.nextElement();
if (entry.getName().endsWith(".class")) {
String name = entry.getName();
name = name.substring(0, name.length() - 6);
name = name.replaceAll("/", ".");
infos.add(name);
}
}
return infos;
} catch (IOException e) {
Assert.fail("解析JAR:" + file + "出现异常,异常消息[" + e.getMessage() + "]");
}
return infos;
}
public static Collection<String> getResources(String filePath, String dirPath) {
List<String> infos = new ArrayList<String>();
try {
JarFile jar = new JarFile(filePath);
Enumeration<JarEntry> d = jar.entries();
while (d.hasMoreElements()) {
JarEntry entry = (JarEntry) d.nextElement();
if (entry.getName().startsWith(dirPath) && !entry.isDirectory()) {
infos.add(entry.getName());
}
}
return infos;
} catch (IOException e) {
Assert.fail("解析JAR:" + filePath + "出现异常,异常消息[" + e.getMessage() + "]");
}
return infos;
}
}
@@ -0,0 +1,73 @@
package com.luqj.util.reflect;
public class MethodParam {
private int index;
private String name;
private Class<?> type;
/**
* 参数的泛型类型集合
*/
private Class<?>[] t;
private Object value;
public MethodParam(int index, String name, Class<?> type) {
super();
this.index = index;
this.name = name;
this.type = type;
}
public Class<?>[] getT() {
return t;
}
public void setT(Class<?>[] ts) {
t = ts;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public String toString() {
return "MethodParam [index=" + index + ", name=" + name + ", type=" + type + "]";
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
}