m-m-m / code

Library to parse, analyze, transform and generate code
Apache License 2.0
2 stars 3 forks source link

Parse full qualified name from Java class #21

Closed jdiazgon closed 5 years ago

jdiazgon commented 5 years ago

As a user of the m-m-m code library, I really would like to have an easy way to parse the full qualified name (FQN) of a Java class so that I can load the compiled class from the class loader (they need FQN in order to find classes).

I need this for the CobiGen CLI because our user selects a Java class as input and we cannot easily get the FQN. There are possible workarounds like traversing parent folders, but I think this solution is much dirtier than implementing it inside this library.

Please find below the API that I used for getting the FQN:

    public static String getQualifiedName(File inputFile, JavaContext context) {

        String className = inputFile.getName().replace(".java", "");
        BaseFile file = createFile(className, context);
        JavaSourceCodeParserImpl parser = new JavaSourceCodeParserImpl();

        try (Reader reader = new FileReader(inputFile.getAbsolutePath())) {
            return parser.parseQualifiedName(reader, file);
        } catch (IOException e) {
            throw new RuntimeIoException(e, IoMode.READ);
        }
    }
hohwille commented 5 years ago

As already discussed, the current hand-written Java Parser is a pure temporary hack. We will generate the parser with AntLR from a grammar file as otherwise we will never be able to support and maintain future java versions and their evolving syntax. Hence the feature you are requesting can be reasonable be provided here are a stable API or in other words it is misplaced. Also it is IMHO a waste/overhead to parse a Java file only for the sake of retrieving the package from it as you can directly derive the package from the path to the file. If that is not conform then coders are violating Java conventions so heavily that they do not earn any support for CobiGen, mmm-code, or whatever tooling.

jdiazgon commented 5 years ago

as you can directly derive the package from the path to the file. If that is not conform then coders are violating Java conventions so heavily that they do not earn any support for CobiGen

Okay, I agree. I'm going to close this issue and I will change the code on the CLI.

hohwille commented 5 years ago

What could however be done by mmm-code is the following. I you have a JavaMavenContext you could provide a File potentially pointing to some Java file within the project to some method that would then return the File to the root of the source directory (or the relative path from there to the Java file) by matching the source and testSource directories of the entire maven multi-module project. With this API you could quite reliable derive the qualified name without actually opening the file.