Get qualified type from DeclaredType/TypeMirror with Java doc API












3















I have a DeclaredType of a field and I would like to get the fully qualified type (raw type?) of the field. For example if the field is:



public static Optional<String> foo;


I would like to get java.util.Optional.



Currently I can get the package name with:



env.getElementUtils().getPackageOf(declaredType.asElement());


I can get the type arguments of the type however I come back to the same problem I end up with a List of TypeMirror which I don't know how to get the qualified name of the types.



I have noticed that I can call TypeMirror#toString() and that will return (for the above) something like:



java.util.Optional<java.lang.String>


I guess I could then cut of everything in front of < but that feels like a hack.



For reference this is how I am getting the field:



private VariableElement getFieldWithName(DocletEnvironment environment, TypeElement classDoc, String fieldName) {
for(VariableElement e : ElementFilter.fieldsIn(environment.getElementUtils().getAllMembers(classDoc))) {
if(e.getSimpleName().toString().equals(fieldName)) {
return e;
}
}
return null;
}

TypeElement classElement = env.getElementUtils().getTypeElement(MyClass.class.getCanonicalName());
VariableElement fieldDoc = getFieldWithName(env, classElement, "foo");
DeclaredType declaredType = (DeclaredType) fieldDoc.asType();









share|improve this question





























    3















    I have a DeclaredType of a field and I would like to get the fully qualified type (raw type?) of the field. For example if the field is:



    public static Optional<String> foo;


    I would like to get java.util.Optional.



    Currently I can get the package name with:



    env.getElementUtils().getPackageOf(declaredType.asElement());


    I can get the type arguments of the type however I come back to the same problem I end up with a List of TypeMirror which I don't know how to get the qualified name of the types.



    I have noticed that I can call TypeMirror#toString() and that will return (for the above) something like:



    java.util.Optional<java.lang.String>


    I guess I could then cut of everything in front of < but that feels like a hack.



    For reference this is how I am getting the field:



    private VariableElement getFieldWithName(DocletEnvironment environment, TypeElement classDoc, String fieldName) {
    for(VariableElement e : ElementFilter.fieldsIn(environment.getElementUtils().getAllMembers(classDoc))) {
    if(e.getSimpleName().toString().equals(fieldName)) {
    return e;
    }
    }
    return null;
    }

    TypeElement classElement = env.getElementUtils().getTypeElement(MyClass.class.getCanonicalName());
    VariableElement fieldDoc = getFieldWithName(env, classElement, "foo");
    DeclaredType declaredType = (DeclaredType) fieldDoc.asType();









    share|improve this question



























      3












      3








      3








      I have a DeclaredType of a field and I would like to get the fully qualified type (raw type?) of the field. For example if the field is:



      public static Optional<String> foo;


      I would like to get java.util.Optional.



      Currently I can get the package name with:



      env.getElementUtils().getPackageOf(declaredType.asElement());


      I can get the type arguments of the type however I come back to the same problem I end up with a List of TypeMirror which I don't know how to get the qualified name of the types.



      I have noticed that I can call TypeMirror#toString() and that will return (for the above) something like:



      java.util.Optional<java.lang.String>


      I guess I could then cut of everything in front of < but that feels like a hack.



      For reference this is how I am getting the field:



      private VariableElement getFieldWithName(DocletEnvironment environment, TypeElement classDoc, String fieldName) {
      for(VariableElement e : ElementFilter.fieldsIn(environment.getElementUtils().getAllMembers(classDoc))) {
      if(e.getSimpleName().toString().equals(fieldName)) {
      return e;
      }
      }
      return null;
      }

      TypeElement classElement = env.getElementUtils().getTypeElement(MyClass.class.getCanonicalName());
      VariableElement fieldDoc = getFieldWithName(env, classElement, "foo");
      DeclaredType declaredType = (DeclaredType) fieldDoc.asType();









      share|improve this question
















      I have a DeclaredType of a field and I would like to get the fully qualified type (raw type?) of the field. For example if the field is:



      public static Optional<String> foo;


      I would like to get java.util.Optional.



      Currently I can get the package name with:



      env.getElementUtils().getPackageOf(declaredType.asElement());


      I can get the type arguments of the type however I come back to the same problem I end up with a List of TypeMirror which I don't know how to get the qualified name of the types.



      I have noticed that I can call TypeMirror#toString() and that will return (for the above) something like:



      java.util.Optional<java.lang.String>


      I guess I could then cut of everything in front of < but that feels like a hack.



      For reference this is how I am getting the field:



      private VariableElement getFieldWithName(DocletEnvironment environment, TypeElement classDoc, String fieldName) {
      for(VariableElement e : ElementFilter.fieldsIn(environment.getElementUtils().getAllMembers(classDoc))) {
      if(e.getSimpleName().toString().equals(fieldName)) {
      return e;
      }
      }
      return null;
      }

      TypeElement classElement = env.getElementUtils().getTypeElement(MyClass.class.getCanonicalName());
      VariableElement fieldDoc = getFieldWithName(env, classElement, "foo");
      DeclaredType declaredType = (DeclaredType) fieldDoc.asType();






      java javadoc java-11






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 4 at 1:07







      Luke

















      asked Dec 31 '18 at 0:46









      LukeLuke

      1899




      1899
























          2 Answers
          2






          active

          oldest

          votes


















          0














          I tested this code and it works on Apache Netbeans 10 and Jdk11.
          Use ((DeclaredType) variableElement.asType()).asElement().toString():



                      DeclaredType declaredType = (DeclaredType) e.asType();//e is VariableElement from the loop
          fullyQualifiedName = declaredType.asElement().toString();


          Test Classes:



          class MyClass1 {
          public static Optional<String> foo;
          public static List<String> newList;
          public static MyClass2 obj;
          public Media media;
          public void calculate(Double dl) {
          }}

          class MyClass2 extends MyClass1{
          public static Color cl;
          }


          And the Doclet implementation:



          public class TestVarElement implements Doclet {

          public void testFields(DocletEnvironment env) {
          TypeElement typeElement = env.getElementUtils().getTypeElement(MyClass1.class.getCanonicalName());
          System.out.println("Test for 'foo': "+getFieldWithName(env,typeElement,"foo"));
          System.out.println("Test for 'newList': "+getFieldWithName(env,typeElement,"newList"));
          System.out.println("Test for 'obj': "+getFieldWithName(env,typeElement,"obj"));
          System.out.println("Test for 'media': "+getFieldWithName(env,typeElement,"media"));
          }

          private String getFieldWithName(DocletEnvironment env, TypeElement classDoc, String fieldName) {
          String fullyQualifiedName = "";
          for (VariableElement e : ElementFilter.fieldsIn(env.getElementUtils().getAllMembers(classDoc))) {
          if (e.getSimpleName().toString().equals(fieldName)) {
          DeclaredType declaredType = (DeclaredType) e.asType(); //The type of the VariableElement
          fullyQualifiedName = declaredType.asElement().toString(); //Get the fqn
          break;
          }
          }
          return fullyQualifiedName;
          }
          @Override
          public boolean run(DocletEnvironment docEnv) {
          testFields(docEnv);
          return true;
          }

          ... Other Overrids

          }


          Debug/Run the program:



               public class NewClass {
          public static void main(String args) {
          ToolProvider javadoc=ToolProvider.findFirst("javadoc").orElseThrow();
          int result=javadoc.run(System.out, System.err, new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});

          //The following is for java 8 or older, the implementation is diferent where `start` method is used instead of `run`.
          //Main.execute (new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});
          }
          }


          Output




          Test for 'foo': java.util.Optional



          Test for 'newList': java.util.List



          Test for 'obj': pk.MyClass2



          Test for 'media': javax.print.attribute.standard.Media







          share|improve this answer

































            0














            To convert a Generic type to its raw base, resolve it without any type arguments. See Types#getDeclaredType which can be called without specifying any types:




            If zero, and if the type element is generic, then the type element's raw type is returned




            DeclaredType rawType = env.getTypeUtils().getDeclaredType(typeElement);





            share|improve this answer


























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53982637%2fget-qualified-type-from-declaredtype-typemirror-with-java-doc-api%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              I tested this code and it works on Apache Netbeans 10 and Jdk11.
              Use ((DeclaredType) variableElement.asType()).asElement().toString():



                          DeclaredType declaredType = (DeclaredType) e.asType();//e is VariableElement from the loop
              fullyQualifiedName = declaredType.asElement().toString();


              Test Classes:



              class MyClass1 {
              public static Optional<String> foo;
              public static List<String> newList;
              public static MyClass2 obj;
              public Media media;
              public void calculate(Double dl) {
              }}

              class MyClass2 extends MyClass1{
              public static Color cl;
              }


              And the Doclet implementation:



              public class TestVarElement implements Doclet {

              public void testFields(DocletEnvironment env) {
              TypeElement typeElement = env.getElementUtils().getTypeElement(MyClass1.class.getCanonicalName());
              System.out.println("Test for 'foo': "+getFieldWithName(env,typeElement,"foo"));
              System.out.println("Test for 'newList': "+getFieldWithName(env,typeElement,"newList"));
              System.out.println("Test for 'obj': "+getFieldWithName(env,typeElement,"obj"));
              System.out.println("Test for 'media': "+getFieldWithName(env,typeElement,"media"));
              }

              private String getFieldWithName(DocletEnvironment env, TypeElement classDoc, String fieldName) {
              String fullyQualifiedName = "";
              for (VariableElement e : ElementFilter.fieldsIn(env.getElementUtils().getAllMembers(classDoc))) {
              if (e.getSimpleName().toString().equals(fieldName)) {
              DeclaredType declaredType = (DeclaredType) e.asType(); //The type of the VariableElement
              fullyQualifiedName = declaredType.asElement().toString(); //Get the fqn
              break;
              }
              }
              return fullyQualifiedName;
              }
              @Override
              public boolean run(DocletEnvironment docEnv) {
              testFields(docEnv);
              return true;
              }

              ... Other Overrids

              }


              Debug/Run the program:



                   public class NewClass {
              public static void main(String args) {
              ToolProvider javadoc=ToolProvider.findFirst("javadoc").orElseThrow();
              int result=javadoc.run(System.out, System.err, new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});

              //The following is for java 8 or older, the implementation is diferent where `start` method is used instead of `run`.
              //Main.execute (new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});
              }
              }


              Output




              Test for 'foo': java.util.Optional



              Test for 'newList': java.util.List



              Test for 'obj': pk.MyClass2



              Test for 'media': javax.print.attribute.standard.Media







              share|improve this answer






























                0














                I tested this code and it works on Apache Netbeans 10 and Jdk11.
                Use ((DeclaredType) variableElement.asType()).asElement().toString():



                            DeclaredType declaredType = (DeclaredType) e.asType();//e is VariableElement from the loop
                fullyQualifiedName = declaredType.asElement().toString();


                Test Classes:



                class MyClass1 {
                public static Optional<String> foo;
                public static List<String> newList;
                public static MyClass2 obj;
                public Media media;
                public void calculate(Double dl) {
                }}

                class MyClass2 extends MyClass1{
                public static Color cl;
                }


                And the Doclet implementation:



                public class TestVarElement implements Doclet {

                public void testFields(DocletEnvironment env) {
                TypeElement typeElement = env.getElementUtils().getTypeElement(MyClass1.class.getCanonicalName());
                System.out.println("Test for 'foo': "+getFieldWithName(env,typeElement,"foo"));
                System.out.println("Test for 'newList': "+getFieldWithName(env,typeElement,"newList"));
                System.out.println("Test for 'obj': "+getFieldWithName(env,typeElement,"obj"));
                System.out.println("Test for 'media': "+getFieldWithName(env,typeElement,"media"));
                }

                private String getFieldWithName(DocletEnvironment env, TypeElement classDoc, String fieldName) {
                String fullyQualifiedName = "";
                for (VariableElement e : ElementFilter.fieldsIn(env.getElementUtils().getAllMembers(classDoc))) {
                if (e.getSimpleName().toString().equals(fieldName)) {
                DeclaredType declaredType = (DeclaredType) e.asType(); //The type of the VariableElement
                fullyQualifiedName = declaredType.asElement().toString(); //Get the fqn
                break;
                }
                }
                return fullyQualifiedName;
                }
                @Override
                public boolean run(DocletEnvironment docEnv) {
                testFields(docEnv);
                return true;
                }

                ... Other Overrids

                }


                Debug/Run the program:



                     public class NewClass {
                public static void main(String args) {
                ToolProvider javadoc=ToolProvider.findFirst("javadoc").orElseThrow();
                int result=javadoc.run(System.out, System.err, new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});

                //The following is for java 8 or older, the implementation is diferent where `start` method is used instead of `run`.
                //Main.execute (new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});
                }
                }


                Output




                Test for 'foo': java.util.Optional



                Test for 'newList': java.util.List



                Test for 'obj': pk.MyClass2



                Test for 'media': javax.print.attribute.standard.Media







                share|improve this answer




























                  0












                  0








                  0







                  I tested this code and it works on Apache Netbeans 10 and Jdk11.
                  Use ((DeclaredType) variableElement.asType()).asElement().toString():



                              DeclaredType declaredType = (DeclaredType) e.asType();//e is VariableElement from the loop
                  fullyQualifiedName = declaredType.asElement().toString();


                  Test Classes:



                  class MyClass1 {
                  public static Optional<String> foo;
                  public static List<String> newList;
                  public static MyClass2 obj;
                  public Media media;
                  public void calculate(Double dl) {
                  }}

                  class MyClass2 extends MyClass1{
                  public static Color cl;
                  }


                  And the Doclet implementation:



                  public class TestVarElement implements Doclet {

                  public void testFields(DocletEnvironment env) {
                  TypeElement typeElement = env.getElementUtils().getTypeElement(MyClass1.class.getCanonicalName());
                  System.out.println("Test for 'foo': "+getFieldWithName(env,typeElement,"foo"));
                  System.out.println("Test for 'newList': "+getFieldWithName(env,typeElement,"newList"));
                  System.out.println("Test for 'obj': "+getFieldWithName(env,typeElement,"obj"));
                  System.out.println("Test for 'media': "+getFieldWithName(env,typeElement,"media"));
                  }

                  private String getFieldWithName(DocletEnvironment env, TypeElement classDoc, String fieldName) {
                  String fullyQualifiedName = "";
                  for (VariableElement e : ElementFilter.fieldsIn(env.getElementUtils().getAllMembers(classDoc))) {
                  if (e.getSimpleName().toString().equals(fieldName)) {
                  DeclaredType declaredType = (DeclaredType) e.asType(); //The type of the VariableElement
                  fullyQualifiedName = declaredType.asElement().toString(); //Get the fqn
                  break;
                  }
                  }
                  return fullyQualifiedName;
                  }
                  @Override
                  public boolean run(DocletEnvironment docEnv) {
                  testFields(docEnv);
                  return true;
                  }

                  ... Other Overrids

                  }


                  Debug/Run the program:



                       public class NewClass {
                  public static void main(String args) {
                  ToolProvider javadoc=ToolProvider.findFirst("javadoc").orElseThrow();
                  int result=javadoc.run(System.out, System.err, new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});

                  //The following is for java 8 or older, the implementation is diferent where `start` method is used instead of `run`.
                  //Main.execute (new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});
                  }
                  }


                  Output




                  Test for 'foo': java.util.Optional



                  Test for 'newList': java.util.List



                  Test for 'obj': pk.MyClass2



                  Test for 'media': javax.print.attribute.standard.Media







                  share|improve this answer















                  I tested this code and it works on Apache Netbeans 10 and Jdk11.
                  Use ((DeclaredType) variableElement.asType()).asElement().toString():



                              DeclaredType declaredType = (DeclaredType) e.asType();//e is VariableElement from the loop
                  fullyQualifiedName = declaredType.asElement().toString();


                  Test Classes:



                  class MyClass1 {
                  public static Optional<String> foo;
                  public static List<String> newList;
                  public static MyClass2 obj;
                  public Media media;
                  public void calculate(Double dl) {
                  }}

                  class MyClass2 extends MyClass1{
                  public static Color cl;
                  }


                  And the Doclet implementation:



                  public class TestVarElement implements Doclet {

                  public void testFields(DocletEnvironment env) {
                  TypeElement typeElement = env.getElementUtils().getTypeElement(MyClass1.class.getCanonicalName());
                  System.out.println("Test for 'foo': "+getFieldWithName(env,typeElement,"foo"));
                  System.out.println("Test for 'newList': "+getFieldWithName(env,typeElement,"newList"));
                  System.out.println("Test for 'obj': "+getFieldWithName(env,typeElement,"obj"));
                  System.out.println("Test for 'media': "+getFieldWithName(env,typeElement,"media"));
                  }

                  private String getFieldWithName(DocletEnvironment env, TypeElement classDoc, String fieldName) {
                  String fullyQualifiedName = "";
                  for (VariableElement e : ElementFilter.fieldsIn(env.getElementUtils().getAllMembers(classDoc))) {
                  if (e.getSimpleName().toString().equals(fieldName)) {
                  DeclaredType declaredType = (DeclaredType) e.asType(); //The type of the VariableElement
                  fullyQualifiedName = declaredType.asElement().toString(); //Get the fqn
                  break;
                  }
                  }
                  return fullyQualifiedName;
                  }
                  @Override
                  public boolean run(DocletEnvironment docEnv) {
                  testFields(docEnv);
                  return true;
                  }

                  ... Other Overrids

                  }


                  Debug/Run the program:



                       public class NewClass {
                  public static void main(String args) {
                  ToolProvider javadoc=ToolProvider.findFirst("javadoc").orElseThrow();
                  int result=javadoc.run(System.out, System.err, new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});

                  //The following is for java 8 or older, the implementation is diferent where `start` method is used instead of `run`.
                  //Main.execute (new String{"-doclet",TestVarElement.class.getName(),"C:\Users\Super3\Documents\NetBeansProjects\Myproject\src\pk\TestVarElement.java"});
                  }
                  }


                  Output




                  Test for 'foo': java.util.Optional



                  Test for 'newList': java.util.List



                  Test for 'obj': pk.MyClass2



                  Test for 'media': javax.print.attribute.standard.Media








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 5 at 15:17

























                  answered Jan 5 at 12:12









                  TiyebMTiyebM

                  1,5481133




                  1,5481133

























                      0














                      To convert a Generic type to its raw base, resolve it without any type arguments. See Types#getDeclaredType which can be called without specifying any types:




                      If zero, and if the type element is generic, then the type element's raw type is returned




                      DeclaredType rawType = env.getTypeUtils().getDeclaredType(typeElement);





                      share|improve this answer






























                        0














                        To convert a Generic type to its raw base, resolve it without any type arguments. See Types#getDeclaredType which can be called without specifying any types:




                        If zero, and if the type element is generic, then the type element's raw type is returned




                        DeclaredType rawType = env.getTypeUtils().getDeclaredType(typeElement);





                        share|improve this answer




























                          0












                          0








                          0







                          To convert a Generic type to its raw base, resolve it without any type arguments. See Types#getDeclaredType which can be called without specifying any types:




                          If zero, and if the type element is generic, then the type element's raw type is returned




                          DeclaredType rawType = env.getTypeUtils().getDeclaredType(typeElement);





                          share|improve this answer















                          To convert a Generic type to its raw base, resolve it without any type arguments. See Types#getDeclaredType which can be called without specifying any types:




                          If zero, and if the type element is generic, then the type element's raw type is returned




                          DeclaredType rawType = env.getTypeUtils().getDeclaredType(typeElement);






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 15 at 11:32

























                          answered Mar 15 at 10:32









                          drekbourdrekbour

                          187110




                          187110






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53982637%2fget-qualified-type-from-declaredtype-typemirror-with-java-doc-api%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              MongoDB - Not Authorized To Execute Command

                              in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                              Npm cannot find a required file even through it is in the searched directory