fixed package path return null in executable jar

This commit is contained in:
jinyu 2017-08-28 20:38:07 +08:00
parent fa2bef41fd
commit c195989e33

View File

@ -28,180 +28,192 @@ import java.util.jar.JarFile;
* @see * @see
*/ */
public final class ClassUtil { public final class ClassUtil {
private final static String POINT = "."; private final static String POINT = ".";
private final static String CLASS = ".class"; private final static String CLASS = ".class";
/** /**
* 获取某个包下所有的class信息 * 获取某个包下所有的class信息
* *
* @param packageName * @param packageName
* 包名 * 包名
* @return * @return
*/ */
public static List<Class<?>> getClasses(String packageName) { public static List<Class<?>> getClasses(String packageName) {
String packageFileName = packageName.replace(POINT, File.separator); String packageFileName = packageName.replace(POINT, File.separator);
URL fullPath = getDefaultClassLoader().getResource(packageFileName); URL fullPath = getDefaultClassLoader().getResource(packageFileName);
String protocol = fullPath.getProtocol(); if (fullPath == null) {
if (protocol.equals(ServerToolkits.PROTOCOL_FILE)) { fullPath = ClassUtil.class.getClassLoader().getResource(
try { packageFileName);
File dir = new File(fullPath.toURI()); }
return findClassesByFile(dir, packageName); String protocol = fullPath.getProtocol();
} catch (URISyntaxException e) { if (protocol.equals(ServerToolkits.PROTOCOL_FILE)) {
throw new RuntimeException(e); try {
} File dir = new File(fullPath.toURI());
} else if (protocol.equals(ServerToolkits.PROTOCOL_JAR)) { return findClassesByFile(dir, packageName);
try { } catch (URISyntaxException e) {
return findClassesByJar(((JarURLConnection) fullPath.openConnection()).getJarFile(), packageName); throw new RuntimeException(e);
} catch (IOException e) { }
throw new RuntimeException(e); } else if (protocol.equals(ServerToolkits.PROTOCOL_JAR)) {
} try {
} return findClassesByJar(
return null; ((JarURLConnection) fullPath.openConnection())
} .getJarFile(),
packageName);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
/** /**
* 扫描目录下所有的class对象 * 扫描目录下所有的class对象
* *
* @param dir * @param dir
* 文件目录 * 文件目录
* @param packageName * @param packageName
* 包的全限类名 * 包的全限类名
* @return * @return
*/ */
private static List<Class<?>> findClassesByFile(File dir, String packageName) { private static List<Class<?>> findClassesByFile(File dir, String packageName) {
List<Class<?>> classes = new ArrayList<Class<?>>(); List<Class<?>> classes = new ArrayList<Class<?>>();
File[] files = dir.listFiles(new FilenameFilter() { File[] files = dir.listFiles(new FilenameFilter() {
@Override @Override
public boolean accept(File file, String name) { public boolean accept(File file, String name) {
return file.isDirectory() || file.getName().endsWith(CLASS); return file.isDirectory() || file.getName().endsWith(CLASS);
} }
}); });
if (files != null) { if (files != null) {
for (File file : files) { for (File file : files) {
if (file.isDirectory()) { if (file.isDirectory()) {
classes.addAll(findClassesByFile(file, packageName + POINT + file.getName())); classes.addAll(findClassesByFile(file, packageName + POINT
} else { + file.getName()));
try { } else {
classes.add(Class.forName(packageName + POINT + file.getName().replace(CLASS, ""))); try {
} catch (ClassNotFoundException e) { classes.add(Class.forName(packageName + POINT
; + file.getName().replace(CLASS, "")));
} } catch (ClassNotFoundException e) {
} ;
} }
} }
return classes; }
} }
return classes;
}
/** /**
* 扫描jar包下所有的class对象 * 扫描jar包下所有的class对象
* *
* @param jar * @param jar
* jar包对象 * jar包对象
* @param packageName * @param packageName
* 包的全限类名 * 包的全限类名
* @return * @return
*/ */
private static List<Class<?>> findClassesByJar(JarFile jar, String packageName) { private static List<Class<?>> findClassesByJar(JarFile jar,
List<Class<?>> classes = new ArrayList<Class<?>>(); String packageName) {
Enumeration<JarEntry> jarEntries = jar.entries(); List<Class<?>> classes = new ArrayList<Class<?>>();
while (jarEntries.hasMoreElements()) { Enumeration<JarEntry> jarEntries = jar.entries();
JarEntry jarEntry = jarEntries.nextElement(); while (jarEntries.hasMoreElements()) {
if (jarEntry.isDirectory()) { JarEntry jarEntry = jarEntries.nextElement();
continue; if (jarEntry.isDirectory()) {
} continue;
String className = jarEntry.getName().replace(File.separator, POINT); }
if (!className.startsWith(packageName) || !className.endsWith(CLASS)) { String className = jarEntry.getName()
continue; .replace(File.separator, POINT);
} if (!className.startsWith(packageName)
try { || !className.endsWith(CLASS)) {
classes.add(Class.forName(className.replace(CLASS, ""))); continue;
} catch (ClassNotFoundException e) { }
; try {
} classes.add(Class.forName(className.replace(CLASS, "")));
} } catch (ClassNotFoundException e) {
return classes; ;
} }
}
return classes;
}
public static Object deepClone(Object obj) { public static Object deepClone(Object obj) {
ByteArrayOutputStream bos = null; ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null; ObjectOutputStream oos = null;
ByteArrayInputStream bis = null; ByteArrayInputStream bis = null;
ObjectInputStream ois = null; ObjectInputStream ois = null;
try { try {
bos = new ByteArrayOutputStream(); bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos); oos = new ObjectOutputStream(bos);
oos.writeObject(obj); oos.writeObject(obj);
bis = new ByteArrayInputStream(bos.toByteArray()); bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis); ois = new ObjectInputStream(bis);
return ois.readObject(); return ois.readObject();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} finally { } finally {
try { try {
if (bos != null) { if (bos != null) {
bos.close(); bos.close();
} }
if (oos != null) { if (oos != null) {
oos.close(); oos.close();
} }
if (bis != null) { if (bis != null) {
bis.close(); bis.close();
} }
if (ois != null) { if (ois != null) {
ois.close(); ois.close();
} }
} catch (IOException e) { } catch (IOException e) {
;// ignore ;// ignore
} }
} }
} }
/** /**
* 获得泛型类型 * 获得泛型类型
* *
* @param object * @param object
* @return * @return
*/ */
public static Class<?> getGenericType(Class<?> clazz) { public static Class<?> getGenericType(Class<?> clazz) {
if (clazz == Object.class) { if (clazz == Object.class) {
return null; return null;
} }
Type type = clazz.getGenericSuperclass(); Type type = clazz.getGenericSuperclass();
if (type instanceof ParameterizedType) { if (type instanceof ParameterizedType) {
ParameterizedType ptype = ((ParameterizedType) type); ParameterizedType ptype = ((ParameterizedType) type);
Type[] args = ptype.getActualTypeArguments(); Type[] args = ptype.getActualTypeArguments();
return (Class<?>) args[0]; return (Class<?>) args[0];
} }
return getGenericType(clazz.getSuperclass()); return getGenericType(clazz.getSuperclass());
} }
public static ClassLoader getDefaultClassLoader() { public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null; ClassLoader cl = null;
try { try {
cl = Thread.currentThread().getContextClassLoader(); cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) { } catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back... // Cannot access thread context ClassLoader - falling back...
} }
if (cl == null) { if (cl == null) {
// No thread context class loader -> use class loader of this class. // No thread context class loader -> use class loader of this class.
cl = ClassUtil.class.getClassLoader(); cl = ClassUtil.class.getClassLoader();
if (cl == null) { if (cl == null) {
// getClassLoader() returning null indicates the bootstrap // getClassLoader() returning null indicates the bootstrap
// ClassLoader // ClassLoader
try { try {
cl = ClassLoader.getSystemClassLoader(); cl = ClassLoader.getSystemClassLoader();
} catch (Throwable ex) { } catch (Throwable ex) {
// Cannot access system ClassLoader - oh well, maybe the // Cannot access system ClassLoader - oh well, maybe the
// caller can live with null... // caller can live with null...
} }
} }
} }
return cl; return cl;
} }
public static void main(String[] args) { public static void main(String[] args) {
System.err.println(getClasses("com.foxinmy.weixin4j.qy.event")); System.err.println(getClasses("com.foxinmy.weixin4j.qy.event"));
} }
} }