mercredi 11 mars 2020

Get all method with annotation @Test in all class in all JAR Files

I want take all mehod with @Test in all JAR file with many class. i have my main in src/main/java/it/anas/testsuiteloader/controller.java and jar file in src/main/java/test/* <---test is a package

my code is:

             //TAKE ALL JAR FILE
             List<JarFile> jarList = Files.walk(Paths.get("src/main/java/test"))
            .filter(f -> f.toString().endsWith(".jar"))
            .map(Path::toFile).map(f -> {
                try {
                    return new JarFile(f);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            })
            .collect(Collectors.toList());

     //in all jar, in all class in all method

     for (JarFile j : jarList) {
         for (Enumeration<JarEntry> entries = j.entries(); entries.hasMoreElements(); ) {
            JarEntry entry = entries.nextElement();
            String file = entry.getName();

            if (file.endsWith(".class")) {
                String classname = file.replaceAll("/", ".")
                        .substring(0, file.lastIndexOf("."));


                try {
                    Class<?> currentClass = Class.forName(classname); <----ERROR!!!!
                    List<String> testMethods = new ArrayList<>();
                    for (int i = 0; i < currentClass.getMethods().length; i++) {
                        Method method = currentClass.getMethods()[i];
                        Annotation ann = method.getAnnotation(Test.class);
                        if (ann != null) {
                            testMethods.add(method.getName());
                        }
                    }//fine for metodi
                    if (testMethods.size() >1) {
                        testClassObjList.put(j.toString(),classname,testMethods);
                        System.out.format("%s %s %s",j.toString(),classname,testMethods);
                    }
                } catch (Throwable e) {System.out.println("WARNING: failed to instantiate " + classname + " from " + file); }

            }
        }

It take correct class name:

String classname = file.replaceAll("/", ".")
                        .substring(0, file.lastIndexOf("."));  //<----- IS OK i view here class name

But here i have error:

Class<?> currentClass = Class.forName(classname);  //<-----ERROR no class found! 

Some TIPS??? How i search class in JAR file?? thanks Regards





Aucun commentaire:

Enregistrer un commentaire