io.github.whimthen.kits.EnvKit Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kits Show documentation
Show all versions of kits Show documentation
Easy to use java tool library.
package io.github.whimthen.kits;
import io.github.whimthen.kits.log.Logger;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
/**
* 全局工具类
*
* @project: kits
* @created: with IDEA
* @author: kits
* @Date: 2018 08 20 上午11:0710 | 八月. 星期一
*/
public class EnvKit {
/**
* 判断是否有的参数为空: 是-true | 否-false
*
* @param objects 需要校验的参数
* @return
*/
public static boolean hasNullOrEmpty(Object... objects) {
for (Object obj: objects) {
if (Objects.isNull(obj)) {
return true;
} else if (obj instanceof String && StringKit.isNullOrEmpty((String) obj)) {
return true;
}
}
return false;
}
/**
* 判断是否不包含空值: 不包含-true | 包含-false
*
* @param args
* @return
*/
public static boolean notHasNullOrEmpty(Object... args) {
return !hasNullOrEmpty(args);
}
/**
* 判断是否是win系统
*
* @return 是(true)
*/
public static boolean isWin() {
String osName = System.getProperty("os.name");
return osName.toLowerCase().contains("win");
}
/**
* 判断是否不是win系统
*
* @return 不是(true)
*/
public static boolean isNotWin() {
return !isWin();
}
/**
* 获取当前栈信息
*
* @param stackTraceElements 栈信息对象数组
* @return 当前栈信息
*/
public static String getStackElementsMessage(StackTraceElement[] stackTraceElements){
StringBuilder stackInfo = new StringBuilder();
for (StackTraceElement stackTraceElement : stackTraceElements) {
stackInfo.append(stackTraceElement.toString());
stackInfo.append(FileKit.getLineSeparator());
}
return stackInfo.toString().trim();
}
/**
* 获取进程的主线程
*
* @return 进程的主线程
*/
public static Thread getMainThread(){
for(Thread thread: getThreads()){
if(thread.getId() == 1){
return thread;
}
}
return null;
}
/**
* 获取JVM中的所有线程
*
* @return 线程对象数组
*/
public static Thread[] getThreads(){
ThreadGroup group = Thread.currentThread().getThreadGroup().getParent();
int estimatedSize = group.activeCount() * 2;
Thread[] slackList = new Thread[estimatedSize];
int actualSize = group.enumerate(slackList);
Thread[] list = new Thread[actualSize];
System.arraycopy(slackList, 0, list, 0, actualSize);
return list;
}
/**
* 线程休眠
*
* @param milliSeconds 毫秒数
*/
public static void sleep(long milliSeconds) {
try {
TimeUnit.MILLISECONDS.sleep(milliSeconds);
} catch (Exception ex) {
Logger.errorf("The Thread sleep error, Thread: {}", Thread.currentThread().getName());
}
}
/**
* 判读是否是基本类型(null, boolean, byte, char, double, float, int, long, short, string)
*
* @param clazz Class 对象
* @return true: 是基本类型, false:非基本类型
*/
public static boolean isBasicType(Class clazz){
if (clazz == null || clazz.isPrimitive() || clazz.getName().startsWith("java.lang")) {
return true;
} else {
return false;
}
}
/**
* 将对象数组转换成,对象类型的数组
*
* @param objs 对象类型数组
* @return 类数组
*/
public static Class>[] getArrayClasses(Object[] objs){
if (objs == null) {
return new Class>[0];
}
Class>[] parameterTypes= new Class>[objs.length];
for (int i = 0; i < objs.length; i++) {
if (objs[i] == null) {
parameterTypes[i] = Object.class;
} else {
parameterTypes[i] = objs[i].getClass();
}
}
return parameterTypes;
}
/**
* 判读是否是 JDK 中定义的类(java包下的所有类)
*
* @param clazz Class 对象
* @return true: 是JDK 中定义的类, false:非JDK 中定义的类
*/
public static boolean isSystemType(Class clazz){
if( clazz.isPrimitive()){
return true;
}
//排除的包中的 class 不加载
for(String systemPackage : Arrays.asList("java.", "sun.", "javax.", "com.sun", "com.oracle")){
if(clazz.getName().startsWith(systemPackage)){
return true;
}
}
return false;
}
/**
* 判断某个类型是否实现了某个接口
* 包括判断其父接口
* @param type 被判断的类型
* @param interfaceClass 检查是否实现了次类的接口
* @return 是否实现某个接口
*/
public static boolean isImpByInterface(Class> type, Class> interfaceClass){
if (type == interfaceClass) {
return true;
}
Class>[] interfaces = type.getInterfaces();
for (Class> interfaceItem : interfaces) {
if (interfaceItem == interfaceClass) {
return true;
} else {
return isImpByInterface(interfaceItem, interfaceClass);
}
}
return false;
}
/**
* 判断某个类型是否继承于某个类
* 包括判断其父类
* @param type 判断的类型
* @param extendsClass 用于判断的父类类型
* @return 是否继承于某个类
*/
public static boolean isExtendsByClass(Class> type,Class> extendsClass){
if(extendsClass == type){
return true;
}
Class> superClass = type;
do {
if (superClass == extendsClass) {
return true;
}
superClass = superClass.getSuperclass();
} while (superClass != null && Object.class != superClass);
return false;
}
/**
* 获取堆栈信息
*
* @param index 索引
* @return 对应的堆栈
*/
public static StackTraceElement getStaceTraceE(int index) {
Throwable ex = new Throwable();
StackTraceElement[] stackTrace = ex.getStackTrace();
return stackTrace.length > index ? stackTrace[index] : stackTrace[stackTrace.length - 1];
}
/**
* 反射
*
* @param className 类名称
* @return 加载的Class
*/
public static Class forName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
Logger.error(ex);
return null;
}
}
/**
* 查找制定路径下的类
*
* @param classPath
* @return
* @throws IOException
*/
public static List findClass(String classPath) throws IOException {
Set classes = new HashSet<>();
List userClassPath;
if (StringKit.isNullOrEmpty(classPath)) {
userClassPath = FileKit.getClassPath();
} else {
userClassPath = Collections.singletonList(classPath);
}
for (String path : userClassPath) {
File rootFile = new File(path);
if (rootFile.exists() && rootFile.isDirectory()) {
classes.addAll(getDirClass(rootFile));
} else if (rootFile.exists() && !rootFile.isDirectory() && rootFile.getName().endsWith(".jar")) {
classes.addAll(getJarClass(rootFile));
}
}
return new ArrayList<>(classes);
}
/**
* 获取目录下的class
*
* @param rootFile
* @return
* @throws IOException
*/
public static List getDirClass(File rootFile) throws IOException {
List files = FileKit.scanFile(rootFile);
Set classes = new HashSet<>();
if (!files.isEmpty()) {
for (File file: files) {
String fileName = file.getCanonicalPath();
if("class".equals(FileKit.getFileExtension(fileName))) {
//如果是内部类则跳过
if(StringKit.regexMatch(fileName, "\\$\\d\\.class")){
continue;
}
fileName = fileName.replace(rootFile.getCanonicalPath() + File.separator, "");
try {
Class clazz = resourceToClass(fileName);
if (!classes.contains(clazz)) {
classes.add(clazz);
}
} catch (ClassNotFoundException e) {
Logger.errorf("Try to load class[{}] failed", e, fileName);
}
}
}
}
return new ArrayList<>(classes);
}
public static List getJarClass(File jarFile) throws IOException {
Set classes = new HashSet<>();
List jarEntries = FileKit.scanJar(jarFile);
jarEntries.parallelStream()
.filter(jarEntry -> {
if (StringKit.regexMatch(jarEntry.getName(), "\\$\\d\\.class")
&& "class".equals(FileKit.getFileExtension(jarEntry.getName()))) {
return true;
} else {
return false;
}
})
.forEach(jarEntry -> {
String fileName = jarEntry.getName();
try {
Class clazz = resourceToClass(fileName);
classes.add(clazz);
} catch (Throwable e) {
fileName = null;
}
});
return new ArrayList<>(classes);
}
/**
* 查找classPath下的类
*
* @return
* @throws IOException
*/
public static List findClass() throws IOException {
return findClass(null);
}
/**
* 将资源文件路径 转换成 Class
* @param resourcePath 资源资源文件路径
* @return Class对象
* @throws ClassNotFoundException 类未找到异常
*/
public static Class resourceToClass(String resourcePath) throws ClassNotFoundException {
String className;
if(resourcePath.startsWith(File.separator)){
resourcePath = resourcePath.substring(1);
}
className = StringKit.replaceAll(resourcePath, ".class", "\\$.*\\.class$");
className = StringKit.replaceAll(className, "", ".class$");
className = StringKit.replaceAll(className, ".", File.separator);
try {
return Class.forName(className);
} catch (Exception ex) {
throw new ClassNotFoundException("load and define class " + className + " failed");
}
}
}