我有一个代码,用于获取给定包名称中的类文件列表。但是,代码返回给定包(com.testscript)中可用的类文件列表,但是当我使用包(src.com.testscript)运行相同代码的jar时,它不会返回文件夹中可用的类文件列表子文件夹。我把这个jar文件放在包含jar文件和scr包的主文件夹下。下面是我用来获取课程列表的代码。
package com.generateUI.createXML;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
import org.testng.internal.ClassHelper;
import org.testng.internal.annotations.AnnotationHelper;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.annotations.JDK15AnnotationFinder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.setup.CreateMethodsList;
public class FindTestMethodsInTestClass {
public boolean isMethodsListXMLReady() throws ClassNotFoundException, IOException, InterruptedException {
FindTestMethodsInTestClass FTMITC = new FindTestMethodsInTestClass();
boolean bool=false;
boolean isXMLFileExist = false;
Map<String,CreateMethodsList> aMap=new HashMap<String,CreateMethodsList>();
Class[] classes=getClasses("com.testscript");
IAnnotationFinder finder = new JDK15AnnotationFinder(new DummyTransformer());
for(Class cls:classes){
String temp=cls.toString();
String[] className=temp.split("\\.");
String[] classPaht=temp.split(" ");
List<String> mNames=new ArrayList();
Set<Method> allMethods = ClassHelper.getAvailableMethods(cls);
if(!(allMethods==null)){
for (Method eachMethod : allMethods) {
ITestAnnotation value = AnnotationHelper.findTest(finder, eachMethod);
if (value != null) {
mNames.add(eachMethod.getName());
bool=true;
}
}
if(bool){
int lastIndex=className.length-1;
aMap.put(className[lastIndex],new CreateMethodsList(mNames,classPaht[1]));
}
}
}
if(FTMITC.CreateXML(aMap)){
isXMLFileExist=true;
}
return isXMLFileExist;
}
public static class DummyTransformer implements IAnnotationTransformer {
@SuppressWarnings("rawtypes")
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor,
Method testMethod) {
}
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
* @throws ClassNotFoundException
* @throws IOException
*/
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
System.out.println("<URL> resources: "+resources);
while (resources.hasMoreElements()) {
URL resource = new URL( resources.nextElement().toString().replace("%20", " "));
System.out.println("URL Resource: "+resources);
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
System.out.println("<Class> classes: "+resources);
return classes.toArray(new Class[classes.size()]);
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base directory
* @return The classes
* @throws ClassNotFoundException
*/
private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
public boolean CreateXML(Map map) throws InterruptedException{
boolean bool=false;
try {
File file = new File(".\\MethodsList.xml");
if(file.exists()){
file.delete();
Thread.sleep(2000);
}
Set<String> keys=map.keySet();
List<String>methodsName=new ArrayList();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("TestMethodsList");
doc.appendChild(rootElement);
for(String key:keys){
// System.out.println(key);
// classname elements
Element ClassName = doc.createElement(key);
rootElement.appendChild(ClassName);
methodsName=((CreateMethodsList) map.get(key)).getMehodsList();
String path=((CreateMethodsList) map.get(key)).getClassPath();
Element classPath = doc.createElement("classPath");
classPath.appendChild(doc.createTextNode(path));
ClassName.appendChild(classPath);
for(String str:methodsName){
// methodName elements
Element methodName = doc.createElement("methodName");
methodName.appendChild(doc.createTextNode(str));
ClassName.appendChild(methodName);
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
String filePath=".\\MethodsList.xml";
StreamResult result = new StreamResult(new File(filePath).toString().replace("%20", " "));
//StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
if(new File(".\\MethodsList.xml").exists()){
bool=true;
}
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
} catch (ParserConfigurationException pce) {
bool=false;
pce.printStackTrace();
} catch (TransformerException tfe) {
bool=false;
tfe.printStackTrace();
}
return bool;
}
public static void main(String arg[]) throws ClassNotFoundException, IOException, InterruptedException{
FindTestMethodsInTestClass FTMITC=new FindTestMethodsInTestClass();
System.out.println(FTMITC.isMethodsListXMLReady());
}
}
如果您能提供我的意见,我将不胜感激。