JFinal自动扫描表绑定model(包含jar包扫描)

前段时间 @绝望的八皮 写了个自动探测model注册插件,见:http://my.oschina.net/b1412/blog/67764 主要功能是为了省去在系统的config中每个model对应表名的配置,通过注解的方式绑定相应的表名,这样做也为将来实现jfinal组件化分离埋下了很好的伏笔,总体来说还是蛮有意义的。遗憾的是可能由于时间原因,八皮没能完成对jar包中class类绑定的扫描,私下联系过说会抽时间做,奈何需求紧急,自己先应付着写了个粗陋的实现,且等八皮优化版本。

基本事先没有修改,唯一修改的是对class扫描的类ClassSeacher,其余参照以上连接实现,就不一一发了。

 

package net.zfsy.db.plugin;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassSearcher {

	/**
	 * 递归查找文件
	 * 
	 * @param baseDirName
	 *            查找的文件夹路径
	 * @param targetFileName
	 *            需要查找的文件名
	 */
	private static List<String> findFiles(String baseDirName,
			String targetFileName) {
		/**
		 * 算法简述: 从某个给定的需查找的文件夹出发,搜索该文件夹的所有子文件夹及文件,
		 * 若为文件,则进行匹配,匹配成功则加入结果集,若为子文件夹,则进队列。 队列不空,重复上述操作,队列为空,程序结束,返回结果。
		 */
		List<String> classFiles = new ArrayList<String>();
		String tempName = null;
		// 判断目录是否存在
		File baseDir = new File(baseDirName);
		if (!baseDir.exists() || !baseDir.isDirectory()) {
			System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
		} else {
			String[] filelist = baseDir.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(baseDirName + File.separator
						+ filelist[i]);
				if (!readfile.isDirectory()) {
					tempName = readfile.getName();
					if (ClassSearcher.wildcardMatch(targetFileName, tempName)) {
						String classname;
						String tem = readfile.getAbsoluteFile().toString()
								.toString().replaceAll("\\\\", "/");
						classname = tem.substring(tem.indexOf("/classes")
								+ "/classes".length(), tem.indexOf(".class"));
						if (classname.startsWith("/")) {
							classname = classname.substring(classname
									.indexOf("/") + 1);
						}
						classname = className(classname, "/classes");
						classFiles.add(classname);
					}
				} else if (readfile.isDirectory()) {
					classFiles.addAll(findFiles(baseDirName + File.separator
							+ filelist[i], targetFileName));
				}
			}
		}
		return classFiles;
	}
	/**
	 * 查找jar包中的class
	 * @param baseDirName jar路径
	 * @param jarFileURL jar文件地址
	 * @return 
	 */
	public static List<String> findjarFiles(String baseDirName,
			URL... jarFileURL) {
		List<String> classFiles = new ArrayList<String>();
		try {
			// 判断目录是否存在
			File baseDir = new File(baseDirName);
			if (!baseDir.exists() || !baseDir.isDirectory()) {
				System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
			} else {
				String[] filelist = baseDir.list();
				for (int i = 0; i < filelist.length; i++) {
					if (filelist[i].contains("zfplugin")) {//查找含有zfplugin的jar包
						JarFile localJarFile = new JarFile(new File(baseDirName
								+ File.separator + filelist[i]));
						Enumeration<JarEntry> entries = localJarFile.entries();
						while (entries.hasMoreElements()) {
							JarEntry jarEntry = entries.nextElement();
							String entryName = jarEntry.getName();
							if (jarEntry.isDirectory()) {
								// System.out.println(entryName);
							} else if (entryName.endsWith(".class")) {
								String className = entryName.replaceAll("/",
										".").substring(0,
										entryName.length() - 6);
								classFiles.add(className);
							}
						}
					}
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return classFiles;

	}

	public static List<Class> findClasses(Class clazz)
			throws MalformedURLException {
		List<Class> classList = new ArrayList<Class>();
		URL classPathUrl = ClassSearcher.class.getResource("/");
		List<String> classFileList = findFiles(classPathUrl.getFile(),
				"*.class");
		String lib = new File(classPathUrl.getFile()).getParent() + "/lib/";
		List<String> jarclassFiles = findjarFiles(lib, new File(lib).toURL());
		classFileList.addAll(jarclassFiles);
		for (String classFile : classFileList) {
			// String className = className(classFile, "/classes");
			System.out.println(classFile);
			try {
				Class<?> classInFile = Class.forName(classFile);
				if (classInFile.getSuperclass() == clazz) {
					classList.add(classInFile);
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return classList;
	}

	private static String className(String classFile, String pre) {
		String objStr = classFile.replaceAll("\\\\", "/");
		return objStr.replaceAll("/", ".");
	}

	/**
	 * 通配符匹配
	 * 
	 * @param pattern
	 *            通配符模式
	 * @param str
	 *            待匹配的字符串
	 * @return  匹配成功则返回true,否则返回false
	 */
	private static boolean wildcardMatch(String pattern, String str) {
		int patternLength = pattern.length();
		int strLength = str.length();
		int strIndex = 0;
		char ch;
		for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
			ch = pattern.charAt(patternIndex);
			if (ch == '*') {
				// 通配符星号*表示可以匹配任意多个字符
				while (strIndex < strLength) {
					if (wildcardMatch(pattern.substring(patternIndex + 1),
							str.substring(strIndex))) {
						return true;
					}
					strIndex++;
				}
			} else if (ch == '?') {
				// 通配符问号?表示匹配任意一个字符
				strIndex++;
				if (strIndex > strLength) {
					// 表示str中已经没有字符匹配?了。
					return false;
				}
			} else {
				if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
					return false;
				}
				strIndex++;
			}
		}
		return (strIndex == strLength);
	}

	public static void main(String[] args) throws MalformedURLException {
		// URL classPathUrl = ClassSearcher.class.getResource("/");
		// String baseDirName = new File(classPathUrl.getFile()).getParent()
		// + "/lib/";
		// URL url = new File(baseDirName).toURL();
		// ClassSearcher.findjarFiles(baseDirName, url);
		//ClassSearcher.findClasses(Demo.class);
	}
}

转载于:https://my.oschina.net/mousai/blog/81021

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值