java - Handle TypeMirror and Class gracefully -


i'm getting javax annotationprocessing on here, , have run ugly case. i'll illustrate in series of pseudo-code lines describe learning process:

myannotation ann = elementifound.getannotation(myannotation.class); // class<?> clazz = ann.getcustomclass();  // can throw mirroredtypeexception! // classes within compilation unit don't exist in form @ compile time!  // search web , find alternative...  // inspect annotationmirrors (annotationmirror mirror : element.getannotationmirrors()) {   if (mirror.getannotationtype().tostring().equals(annotationtype.getname())) {     // inspect methods on annotation class     (entry<? extends executableelement,? extends annotationvalue> entry : mirror.getelementvalues().entryset()) {       if (entry.getkey().getsimplename().tostring().equals(paramname)) {         return (typemirror) entry.getvalue();       }     }     return null;   } } return null; 

the problem i'm finding out if client code contains core class java.lang.string or java.lang.object class parameter, line:

return (typemirror) entry.getvalue(); 

...results in classcastexception, because annotationprocessor environment kind enough retrieve class object in case.

i've figured out how need typemirror in absence of class - need handle both of them in code now? there way obtain typemirror class object? because can't find one

the solution went problem use processingenvironment cast resultant class objects typemirrors, in cases when got classes instead of typemirrors. seems work well.

annotationvalue annvalue = entry.getvalue(); if (annvalue instanceof typemirror) {   return (typemirror) annvalue; } else {   string valstring = annvalue.getvalue().tostring();   typeelement elem = processingenv.getelementutils().gettypeelement(valstring);   return elem.astype(); } 

Comments