Search code examples
javafile

Can I compile anonymous or inner classes into a single java .class file?


I am writing a Java class that parses log files. The compiled .class file needs to be loaded into a 3rd party monitoring platform (eG) for deployment and invocation. Unfortunately, the 3rd party platform only allows me to upload a single .class file.

My current implementation has a function to find the 'latest' file in a folder that conforms to a file mask (*CJL*.log) and uses 2 anonymous classes, one to filter a directory listing and another to sort a list of files based on ModifiedDt. When I compile this, I get 3 .class files (Monitor.class, Monitor$1.class, Monitor$2.class) which I cannot deploy.

Is it possible to compile the anonymous classes into a single .class file for deployment to the 3rd party monitoring platform?

I have attached the code of my 'Find Lastest file' function for illustration.

private String FindLatestFile(String folderPath) {
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            if (name.endsWith(".log")
                    & name.contains("CJL")) 
                return true;
            else
                return false;
        }
    };

    File dir = new File(folderPath);
    
    File[] files = dir.listFiles(filter);

    if (files.length > 0) {
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.valueOf(f1.lastModified()).compareTo(
                        f2.lastModified());
            }
        });

        File newest = files[files.length - 1];

        return newest.toString;
    } else {
        return "";
    }
}

I suppose it is possible to do this the 'dumb' way by getting a raw file listing and doing the filter/sort myself but I'm worried this will not be performant.

Any Ideas?


Solution

  • No its not possible afaik. I assume a jar also cannot be used.

    A workaround would be to have the class implement the two interfaces to remove the need for the inner classes.

        class MyClass implements FilenameFilter, Comparator<File> {
        ...
    
        public boolean accept(File dir, String name) {
             if (name.endsWith(".log") & name.contains("CJL")) 
                  return true;
             else
                  return false;
        }
    
        public int compare(File f1, File f2) {
             return Long.valueOf(f1.lastModified()).compareTo(
                     f2.lastModified());
        }
    
        private String FindLatestFile(String folderPath) {
    
           File dir = new File(folderPath);
    
           File[] files = dir.listFiles(this);
    
           if (files.length > 0) {
                Arrays.sort(files, this);
    
                File newest = files[files.length - 1];
    
                return newest.toString;
           } else {
                return "";
           }
    }