package com.byd.mes.util; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ClassDiscovery { private static final Log log = LogFactory.getLog(ClassDiscovery.class); public static List findByPackageNames(String webUrl,String interfaceName,String[] packageNames){ final List clazzList=new ArrayList(); if( packageNames == null) return null; for (String string : packageNames) { String url= StringUtils.getStr(string).replace(".", "\\"); File[] files=new File(StringUtils.getStr(webUrl,"WEB-INF\\classes\\",url)).listFiles(); for (File file : files) { String clasName=file.getName().replace(".class",""); try { String packageName=StringUtils.getStr(string,".",clasName); //排除类部类,以及除接口/抽象类的java文件。 if(!StringUtils.contains(packageName, '$') && isFunction(packageName, interfaceName)){ Class class1=Class.forName(packageName).getClass(); Object object=Class.forName(packageName).newInstance(); clazzList.add(object); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } } return clazzList; } private static String getInvokeResult(Object object, Method[] method, int i) throws IllegalAccessException, InvocationTargetException { String result=(String)method[i].invoke(object); return result; } public static List findByDefaultPackageNames(String webUrl,String interfaceName){ String key = "mes.dev["+interfaceName+"]"; log.debug("mes dev key>>>"+key); String packageNamesStr = BeanFactory.getSystemParamters().get(key); log.debug("mes dev >>>"+packageNamesStr); String[] packageNames =packageNamesStr != null ? packageNamesStr.split(",") : new String[0]; return findByPackageNames(webUrl,interfaceName,packageNames); } /** * @param packageName * @param interfaceName * @return * @throws ClassNotFoundException */ private static boolean isFunction(String packageName,String interfaceName) throws ClassNotFoundException{ Class c = Class.forName(packageName).getClass(); if(c==null){ log.debug("this class is null >>>>>> "+c); return false; } if(c.isInterface()){ log.debug("this class is interface >>>>>>" + c); return false; } if(Modifier.isAbstract(c.getModifiers())){ log.debug("this class is abstract >>>>>> "+c); return false; } Class<?>[] interfaces=c.getInterfaces(); if(interfaces == null || interfaces.length == 0){ log.debug("this interfaces is null or length be 0 >>>>>>> "+interfaces); return false; } try { Class class1 = Class.forName(interfaceName).getClass(); if(class1.isAssignableFrom(c)){ return true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } return false; } }