How do I call main method of one class inside anot

2019-09-03 05:40发布

I have a thread that, when the current application closes, must start the main() method of another class.
I included ClassName.main(someStringArray) in the run() of the thread but the method wasn't called. What might have gone wrong?
The Thread I defined:

private class VideoCreator extends Thread{
        public VideoCreator(){
            pathToPass = savePath + "/" + "video.mov";
            passVect.add("-w");
            passVect.add("1280");
            passVect.add("-h");
            passVect.add("800");
            passVect.add("-f");
            passVect.add("25");
            passVect.add("-o");
            passVect.add(pathToPass);
        }
        @Override
        public void run(){
            try{
                jpegFiles = Files.newDirectoryStream(Paths.get(pathToPass).getParent(),"*.jpg");
                for(Path jpegFile : jpegFiles){
                    passVect.add(jpegFile.toString());
                }
            }catch(IOException e){

            }
            try{
                JpegImagesToMovie.main((String[])passVect.toArray());
            }catch(Exception e){
                System.out.println("Dammit Error!");
                e.printStackTrace();
            }
        }
        public void cleanUp(){

        }
        String pathToPass;
        Vector<String> passVect = new Vector<>(100,200);
        DirectoryStream<Path> jpegFiles;
    }

标签: java static main
1条回答
Anthone
2楼-- · 2019-09-03 06:26

Instead of

(String[])passVect.toArray()

you should write

passVect.toArray(new String[passVect.size()])

or (shorter but less performant)

passVect.toArray(new String[0])

The reason is that toArray() will always return an Object[] array, which you cannot convert to a String[] array even if all its members are strings. (The reverse, by the way, is possible: you can pass a String[] in places expecting Object[], which is used by various methods of the Arrays class. In fact, the thing returned from the toArray() method might have been a String[], even if in a standards-compliant implementation it is not. This is the reason why the compiler didn't complain: it doesn't know or care about the internals of the method, and judging from the return type, an explicit cast to an array of a subclass might be possible if the array was created as such.)

The toArray(T[]) call returns an array of the required type, if you pass an array of that type as an argument. If the passed argument has the correct length, it will be used directly; otherwise a new array will be allocated. For this reason, allocating the correct length in the first place will avoid one allocation along the way.

查看更多
登录 后发表回答