您的位置:首页 > 编程语言 > Java开发

Java常用工具类

2016-05-30 00:00 531 查看
摘要: 工具类是Java开发过程中使用广泛,而且还能提高开发效率的一种方法。

`集合操作工具类:
1.判断是否为空:isEmpty()
2.判断是否非空:isNotEmpty()
代码:
import org.apache.commons.collections.CollectionUtils;
import java.util.Collection;
public class CollectionUtil {
/**
* 判断集合是否非空
*/
public static boolean isNotEmpty(Collection<?> collection) {
return CollectionUtils.isNotEmpty(collection);
}

/**
* 判断集合是否为空
*/
public static boolean isEmpty(Collection<?> collection) {
return CollectionUtils.isEmpty(collection);
}
}

类加载器工具类:
1.获取类加载器:Thread.currentThread().getContextClassLoader()
2.获取类路径: getClassPath()
3.加载类文件
4.异常处理
5.判断类型
代码:
import java.net.URL;
public class ClassUtil {
/**
* 获取类加载器:
Thread.currentThread().getContextClassLoader()

*/
public static ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}

/**
* 获取类路径
*/
public static String getClassPath() {
String classpath = "";
URL resource = getClassLoader().getResource("");
if (resource != null) {
classpath = resource.getPath();
}
return classpath;
}

/**
* 加载类(将自动初始化)
*/
public static Class<?> loadClass(String className) {
return loadClass(className, true);
}

/**
* 加载类
*/
public static Class<?> loadClass(String className, boolean isInitialized) {
try {
return Class.forName(className, isInitialized, getClassLoader());
} catch (ClassNotFoundException e) {
throw new RuntimeException("加载类出错:" + e.getMessage(), e);
}
}

/**
* 是否为 int 类型(包括 Integer 类型)
*/
public static boolean isInt(Class<?> type) {
return type.equals(int.class) || type.equals(Integer.class);
}

/**
* 是否为 long 类型(包括 Long 类型)
*/
public static boolean isLong(Class<?> type) {
return type.equals(long.class) || type.equals(Long.class);
}

/**
* 是否为 double 类型(包括 Double 类型)
*/
public static boolean isDouble(Class<?> type) {
return type.equals(double.class) || type.equals(Double.class);
}

/**
* 是否为 String 类型
*/
public static boolean isString(Class<?> type) {
return type.equals(String.class);
}

加载帮助类工具类:
1.编写相应的方法
2.绑定类标识
3.初始化[定义相关的帮助类和实现加载帮助类]
代码:
//导入相关Jar
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class HelperLoader {
private static final Logger logger = LoggerFactory.getLogger(HelperLoader.class);
public static final boolean IS_SERVLET25;
static {
boolean b;
try {
Class.forName("包名.类名$标识名");
b = false;
}
catch(Throwable t) {
b = true;
}
IS_SERVLET25 = b;
logger.info("[fw] servlet25 " + IS_SERVLET25);
}
//存在这个类
private static class 标识名 {}
public static void init() {
// 定义需要加载的 Helper 类
Class<?>[] classList = {
DataSourceHolder.class, //初始化ds
JedisHolder.class, //初始化redis
EntityHelper.class,
ActionHelper.class,
BeanHelper.class
7fe0
,
AopHelper.class,
IocHelper.class,
PluginHelper.class,
};
// 按照顺序加载类
for (Class<?> cls : classList) {
ClassUtil.loadClass(cls.getName());
}
}
}

加载AOP框架工具类:
1.获取ClassScanner[类扫描器]
2.编写相关的代理
3.添加相关的代理
代码:
//导入相关的jar
import java.lang.annotation.Annotation;
import java.util.*;
public class AopHelper {

/**
* 获取 ClassScanner
*/
private static final ClassScanner classScanner = InstanceFactory.getClassScanner();

static {
try {
// 创建 Proxy Map(用于 存放代理类 与 目标类列表 的映射关系)
Map<Class<?>, List<Class<?>>> proxyMap = createProxyMap();
// 创建 Target Map(用于 存放目标类 与 代理类列表 的映射关系)
Map<Class<?>, List<Proxy>> targetMap = createTargetMap(proxyMap);
// 遍历 Target Map
for (Map.Entry<Class<?>, List<Proxy>> targetEntry : targetMap.entrySet()) {
// 分别获取 map 中的 key 与 value
Class<?> targetClass = targetEntry.getKey();
List<Proxy> proxyList = targetEntry.getValue();
// 创建代理实例
Object proxyInstance = ProxyManager.createProxy(targetClass, proxyList);
// 用代理实例覆盖目标实例,并放入 Bean 容器中
BeanHelper.setBean(targetClass, proxyInstance);
}
} catch (Exception e) {
throw new InitializationError("初始化 AopHelper 出错!", e);
}
}

private static Map<Class<?>, List<Class<?>>> createProxyMap() throws Exception {
Map<Class<?>, List<Class<?>>> proxyMap = new LinkedHashMap<Class<?>, List<Class<?>>>();
// 添加相关代理
addPluginProxy(proxyMap);      // 插件代理
addAspectProxy(proxyMap);      // 切面代理
addTransactionProxy(proxyMap); // 事务代理
return proxyMap;
}

private static void addPluginProxy(Map<Class<?>, List<Class<?>>> proxyMap) throws Exception {
// 获取插件包名下父类为 PluginProxy 的所有类(插件代理类)
List<Class<?>> pluginProxyClassList = classScanner.getClassListBySuper(FrameworkConstant.PLUGIN_PACKAGE, PluginProxy.class);
if (CollectionUtil.isNotEmpty(pluginProxyClassList)) {
// 遍历所有插件代理类
for (Class<?> pluginProxyClass : pluginProxyClassList) {
// 创建插件代理类实例
PluginProxy pluginProxy = (PluginProxy) pluginProxyClass.newInstance();
// 将插件代理类及其所对应的目标类列表放入 Proxy Map 中
proxyMap.put(pluginProxyClass, pluginProxy.getTargetClassList());
}
}
}

private static void addAspectProxy(Map<Class<?>, List<Class<?>>> proxyMap) throws Exception {
// 获取切面类(所有继承于 BaseAspect 的类)
List<Class<?>> aspectProxyClassList = ClassHelper.getClassListBySuper(AspectProxy.class);
// 添加插件包下所有的切面类
aspectProxyClassList.addAll(classScanner.getClassListBySuper(FrameworkConstant.PLUGIN_PACKAGE, AspectProxy.class));
// 排序切面类
sortAspectProxyClassList(aspectProxyClassList);
// 遍历切面类
for (Class<?> aspectProxyClass : aspectProxyClassList) {
// 判断 Aspect 注解是否存在
if (aspectProxyClass.isAnnotationPresent(Aspect.class)) {
// 获取 Aspect 注解
Aspect aspect = aspectProxyClass.getAnnotation(Aspect.class);
// 创建目标类列表
List<Class<?>> targetClassList = createTargetClassList(aspect);
// 初始化 Proxy Map
proxyMap.put(aspectProxyClass, targetClassList);
}
}
}

private static void addTransactionProxy(Map<Class<?>, List<Class<?>>> proxyMap) {
// 使用 TransactionProxy 代理所有 Service 类
List<Class<?>> serviceClassList = ClassHelper.getClassListByAnnotation(Service.class);
proxyMap.put(TransactionProxy.class, serviceClassList);
}

private static void sortAspectProxyClassList(List<Class<?>> proxyClassList) {
// 排序代理类列表
Collections.sort(proxyClassList, new Comparator<Class<?>>() {
@Override
public int compare(Class<?> aspect1, Class<?> aspect2) {
if (aspect1.isAnnotationPresent(AspectOrder.class) || aspect2.isAnnotationPresent(AspectOrder.class)) {
// 若有 Order 注解,则优先比较(序号的值越小越靠前)
if (aspect1.isAnnotationPresent(AspectOrder.class)) {
return getOrderValue(aspect1) - getOrderValue(aspect2);
} else {
return getOrderValue(aspect2) - getOrderValue(aspect1);
}
} else {
// 若无 Order 注解,则比较类名(按字母顺序升序排列)
return aspect1.hashCode() - aspect2.hashCode();
}
}

private int getOrderValue(Class<?> aspect) {
return aspect.getAnnotation(AspectOrder.class) != null ? aspect.getAnnotation(AspectOrder.class).value() : 0;
}
});
}

private static List<Class<?>> createTargetClassList(Aspect aspect) throws Exception {
List<Class<?>> targetClassList = new ArrayList<Class<?>>();
// 获取 Aspect 注解的相关属性
String pkg = aspect.pkg();
String cls = aspect.cls();
Class<? extends Annotation> annotation = aspect.annotation();
// 若包名不为空,则需进一步判断类名是否为空
if (StringUtil.isNotEmpty(pkg)) {
if (StringUtil.isNotEmpty(cls)) {
// 若类名不为空,则仅添加该类
targetClassList.add(ClassUtil.loadClass(pkg + "." + cls, false));
} else {
// 若注解不为空且不是 Aspect 注解,则添加指定包名下带有该注解的所有类
if (annotation != null && !annotation.equals(Aspect.class)) {
targetClassList.addAll(classScanner.getClassListByAnnotation(pkg, annotation));
} else {
// 否则添加该包名下所有类
targetClassList.addAll(classScanner.getClassList(pkg));
}
}
} else {
// 若注解不为空且不是 Aspect 注解,则添加应用包名下带有该注解的所有类
if (annotation != null && !annotation.equals(Aspect.class)) {
targetClassList.addAll(ClassHelper.getClassListByAnnotation(annotation));
}
}
return targetClassList;
}

private static Map<Class<?>, List<Proxy>> createTargetMap(Map<Class<?>, List<Class<?>>> proxyMap) throws Exception {
Map<Class<?>, List<Proxy>> targetMap = new HashMap<Class<?>, List<Proxy>>();
// 遍历 Proxy Map
for (Map.Entry<Class<?>, List<Class<?>>> proxyEntry : proxyMap.entrySet()) {
// 分别获取 map 中的 key 与 value
Class<?> proxyClass = proxyEntry.getKey();
List<Class<?>> targetClassList = proxyEntry.getValue();
// 遍历目标类列表
for (Class<?> targetClass : targetClassList) {
// 创建代理类(切面类)实例
Proxy baseAspect = (Proxy) proxyClass.newInstance();
// 初始化 Target Map
if (targetMap.containsKey(targetClass)) {
targetMap.get(targetClass).add(baseAspect);
} else {
List<Proxy> baseAspectList = new ArrayList<Proxy>();
baseAspectList.add(baseAspect);
targetMap.put(targetClass, baseAspectList);
}
}
}
return targetMap;
}
}
}`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: