Code Model Import for Class with Embedded Enum

309 views Asked by At

I'm working on generating some Java classes using CodeModel and I'm having some trouble adding import statements for classes that have embedded static Enum

For example if I have a class and create an instance variable...

Class<?> clazz = getPackageClass();
cls.field(JMod.PRIVATE, codeModel._ref(sourceClass), "testUnderlying");

But this creates code like...

import com.test.platform.xxx.UnderlyingType;
....
private UnderlyingType testUnderlying;

However, if UnderlyingType had a enum field that I want to invoke a static method on (e.g. valueOf)...

private UnderlyingType.EnumType enum;
...
...
UnderlyingType.EnumType.valueOf(xxx);

it seems to confuse CodeModel and instead of having a seprate import and the instance variable I will get

private com.test.platform.xxx.UnderlyingType testUnderlying;

Is it possible invoke the static method without losing the import?

Thanks for your help!

1

There are 1 answers

0
John Ericksen On

There's a comment in the JCodeModel code that mentions why they don't import inner classes:

    /**
     * Returns true if the symbol represented by the short name
     * is "importable".
     */
    public boolean collisions(JDefinedClass enclosingClass) {
        // special case where a generated type collides with a type in package java
        ...
        if(c.outer()!=null)
            return true; // avoid importing inner class to work around 6431987. Also see jaxb issue 166
        }
    ...
    }

Not sure what 6431987 is referring to (possibly an internal SUN bug tracker) but here is the referenced jaxb issue:

https://java.net/jira/si/jira.issueviews:issue-html/JAXB-166/JAXB-166.html

Seems they were having trouble with imports from inner classes colliding.

Worth noting, this fork of JCodeModel fixes this issue: https://github.com/UnquietCode/JCodeModel