java.lang.StringIndexOutOfBoundsException: String index out of range when package name is changed

牧云@^-^@ 提交于 2020-04-30 06:30:37

问题


I want to read the annotations from .class file placed into random folder. I tried this:

            public static void main(String[] args) throws Exception
            {    
                final File folder = new File("/opt/test");
                processAnnotatedFiles(listLocalFilesAndDirsAllLevels(folder));

            }

        public void processAnnotatedFiles(List<File> list) throws IOException, ClassNotFoundException {
            out.println("Directory files size " + list.size());

            for(int i=0; i<list.size(); i++) {
                out.println("File " + list.get(i).getName());

                File file = list.get(i);

                String path = file.getPath();

                String[] authors = getFixFromClassFile(Paths.get(path));
                System.out.println(Arrays.toString(authors));
            }

        }

        public List<File> listLocalFilesAndDirsAllLevels(File baseDir) {

            List<File>  collectedFilesAndDirs = new ArrayList<>();
            Deque<File> remainingDirs = new ArrayDeque<>();

            if(baseDir.exists()) {
                remainingDirs.add(baseDir);

                while(!remainingDirs.isEmpty()) {
                    File dir = remainingDirs.removeLast();
                    List<File> filesInDir = Arrays.asList(dir.listFiles());
                    for(File fileOrDir : filesInDir)  {
                        // We need to process only .class files
                        if(fileOrDir.getName().endsWith(".class")){
                            collectedFilesAndDirs.add(fileOrDir);
                            if(fileOrDir.isDirectory()) {
                                remainingDirs.add(fileOrDir);
                            }
                        }
                    }
                }
            }

            return collectedFilesAndDirs;
        }

        private String[] getFixFromClassFile(Path pathToClass) throws MalformedURLException, ClassNotFoundException {
            // Create class loader based on path
            URLClassLoader loader = new URLClassLoader(new URL[]{pathToClass.toUri().toURL()});

            // convert path to class with package
            String classWithPackage = getClassWithPackageFromPath(pathToClass);

            // Load class dynamically
            Class<?> clazz = loader.loadClass(classWithPackage);
            Fix fix = clazz.getAnnotation(Fix.class);
            if (fix == null) {
                return new String[0];
            }

            return fix.author();
        }

        private String getClassWithPackageFromPath(Path pathToClass) {
            final String packageStartsFrom = "com.";
            final String classFileExtension = ".class";
            final String pathWithDots = pathToClass.toString().replace(File.separator, ".");
            return pathWithDots.substring(pathWithDots.indexOf(packageStartsFrom)).replace(classFileExtension, "");
        }

I get java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1927)

In this part I want to create a package into random dir. It is really hard to create a valid package from path because there is no any rule package names should follow.

Can you give me some advice how this can be fixed?

来源:https://stackoverflow.com/questions/61503095/java-lang-stringindexoutofboundsexception-string-index-out-of-range-when-packag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!