vendredi 11 septembre 2015

Is there a way to assign the Class in Java at Runtime?

Since I am refactoring my code right now, I am trying to first sort out possible code duplicates. As a posible duplicate I see the 2 methods which basically read files: One from FTP and another from local filestructures. The problem is, that they of course use different classes to achieve the same things. The variable directoryListing is the tricky one.

readLogs(boolean useFTP){
// directory Listing of course needs to be of a different type here or not being declared at all 
    File[] directoryListing;
    File dir = Settings.getInputfolder();
    if(useFTP){
            // ftp implementation
            client = new FTPClient();               
            client.connect(Settings.getFtpHost());
            client.enterLocalPassiveMode();
            client.login(Settings.getFtpLoginname(), Settings.getFtpPassword());
            client.setFileType(FTPClient.BINARY_FILE_TYPE);

            //directoryListing should be of type FTPFile[] here
            directoryListing = client.listFiles(Settings.getInputfolder().toString());
    else{
        //directoryListing should be of type File[] in this case
        directoryListing = dir.listFiles();
    }
    if (directoryListing == null) {
            log.error("Input-folder not found:" + dir.getAbsolutePath());
    }
    //I want to be able to iterate - here myFolder might be of type File oder FTPFile
    for (Object myFolder : directoryListing) {
    ...
    ...
    }
}

The only methods I am using later on in the code have the exact same signatures on both File and FTPFile:
getName()
isFile()
isDirectory()
listFiles()
I have used reflections for those e.g.

Method getFolderNameMethod = myFolder.getClass().getMethod("getName");
String name = (String) getFolderNameMethod.invoke(myFolder);

In what way can I achieve a somewhat dynamic declaration of the directoryListing variable?

Thank you very much for your time and advice in advance! :D





Aucun commentaire:

Enregistrer un commentaire