Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7711083
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T01:17:12+00:00 2026-06-01T01:17:12+00:00

How can I get a class reference/TypeElement of a specific identifier at compile time

  • 0

How can I get a class reference/TypeElement of a specific identifier at compile time in Java?

Say I have the following source file, and I want to get a reference to the Pixel class so I can get a list of its member fields.

package com.foo.bar;
class Test {
    class Pixel {
        int x,y,r,g,b;
    }
    Pixel saturate(Pixel p, int value) {...}
}

The Pixel class definition could be nested inside the Test class, or included from a different package where the source is not available.

I am using the javax.tools API to compile the source files, and I define visitor methods so I can view the arguments to each function. The arguments of a function can be iterated using VariableTree var : node.getParameters(), but the type information from var.getType() only triggers visitIdentifier for class names. This identifier is only the simple name Pixel, not the fully-qualified com.foo.bar.Pixel.

I need a way to reverse this identifier into either Pixel.class or into the TypeElement for the definition of the Pixel class, or into the fully-qualified com.foo.bar.Pixel string so I can then use a ClassLoader on it.

A crude way would be to record all class definitions and then try to do compile-time type lookup, but this wouldn’t work for externally-defined classes.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T01:17:13+00:00Added an answer on June 1, 2026 at 1:17 am

    I ended up creating my own class lookup tool. For those that are interested, I’ll include it here.

    Call this with the path name of every source file to be included in the search:

      public void populateClassDefinitions(String path) {
        Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects(path);
        CompilationTask task =
            compiler.getTask(null, fileManager, diagnosticsCollector, null, null, files);
        final JavacTask javacTask = (JavacTask) task;
        parseResult = null;
        try {
          parseResult = javacTask.parse();
        } catch (IOException e) {
          e.printStackTrace();
          return;
        }
        for (CompilationUnitTree tree : parseResult) {
          tree.accept(new TreeScanner<Void, Void>() {
            @Override
            public Void visitCompilationUnit(CompilationUnitTree node, Void p) {
              currentPackage = "";
              ExpressionTree packageName = node.getPackageName();
              if (packageName != null) {
                String packageNameString = String.valueOf(packageName);
                if (packageNameString.length() > 0) {
                  currentPackage = packageNameString;
                }
              }
              TreeScanner<Void, String> visitor = new TreeScanner<Void, String>() {
                @Override
                public Void visitClass(ClassTree node, String packagePrefix) {
                  if (classDefinitions.get(currentPackage) == null) {
                    classDefinitions.put(currentPackage, new HashMap<String, ClassTree>());
                  }
                  classDefinitions.get(currentPackage).put(packagePrefix + node.getSimpleName(), node);
                  return super.visitClass(node, packagePrefix + node.getSimpleName() + ".");
                }
              };
              for (Tree decls : node.getTypeDecls()) {
                decls.accept(visitor, "");
              }
              return super.visitCompilationUnit(node, p);
            }
          }, null);
        }
      }
    

    Call this to search for classes.

      /**
       * Lookup the definition of a class.
       * 
       * Lookup order: 1. Search in the current file: within the current class scope upwards to the
       * root. 2. Search laterally across files with the same package value for implicitly included
       * classes. 3. Check all import statements.
       * 
       * @param pack
       *          Current package ex "edu.illinois.crhc"
       * @param scope
       *          Current scope ex "Test.InnerClass"
       * @param identifier
       *          The partial class name to search for
       * @return ClassTree the definition of this class if found
       */
      ClassLookup lookupClass(CompilationUnitTree packTree, String scope, String identifier) {
        dumpClassTable();
        String pack = packTree.getPackageName().toString();
        System.out.println("Looking for class " + pack + " - " + scope + " - " + identifier);
        // Search nested scope and within same package
        HashMap<String, ClassTree> packClasses = classDefinitions.get(pack);
        if (packClasses != null) {
          String[] scopeWalk = scope.split("\\.");
          for (int i = scopeWalk.length; i >= 0; i--) {
            StringBuilder scopeTest = new StringBuilder();
            for (int j = 0; j < i; j++) {
              scopeTest.append(scopeWalk[j] + ".");
            }
            scopeTest.append(identifier);
            System.out.println("Testing scope " + pack + " - " + scopeTest.toString());
            if (packClasses.containsKey(scopeTest.toString())) {
              return new ClassLookup(packClasses.get(scopeTest.toString()), pack.replace(".", "/")
                  + "/" + scopeTest.toString().replace(".", "$"));
            }
          }
        }
        /*
         * Check if fully-qualified identifier (foo.bar.Widget) is used. This needs to search all
         * combinations of package and class nesting.
         */
        StringBuilder packTest = new StringBuilder();
        String[] qualifiedName = identifier.split("\\.");
        for (int i = 0; i < qualifiedName.length - 1; i++) {
          packTest.append(qualifiedName[i]);
          if (i != qualifiedName.length - 2) {
            packTest.append(".");
          }
        }
        String clazz = qualifiedName[qualifiedName.length - 1];
        System.out.println("Testing absolute identifier: " + packTest.toString() + " " + clazz);
        if (classDefinitions.containsKey(packTest.toString())) {
          HashMap<String, ClassTree> foundPack = classDefinitions.get(packTest.toString());
          if (foundPack.containsKey(clazz)) {
            return new ClassLookup(foundPack.get(clazz), packTest.toString().replace(".", "/") + "/"
                + clazz.replace(".", "$"));
          }
        }
    
        /*
         * Search import statements. Last identifier segment must be class name. Search all of the
         * packages for the identifier by splitting off the class name. a.b.c.Tree Tree.Branch
         * Tree.Branch.Leaf
         */
        for (ImportTree imp : currentPackTree.getImports()) {
          pack = imp.getQualifiedIdentifier().toString();
          System.out.println(pack);
          String[] importName = pack.split("\\.");
          // Split off class name.
          // TODO: (edge case) no package
          StringBuilder importTest = new StringBuilder();
          for (int i = 0; i < importName.length - 1; i++) {
            importTest.append(importName[i]);
            if (i != importName.length - 2) {
              importTest.append(".");
            }
          }
          // See if the last import segment is * or matches the first segment of the identifier.
    
          System.out.println("Testing globally " + importTest.toString() + " - " + identifier);
          if (classDefinitions.containsKey(importTest.toString())) {
            HashMap<String, ClassTree> foundPack = classDefinitions.get(importTest.toString());
            String[] identifierParts = identifier.split(".");
            String importClass = importName[importName.length-1];
            if (importClass.equals("*") || identifierParts[0].equals(importClass)) {
              if (foundPack.containsKey(identifier)) {
                return new ClassLookup(foundPack.get(identifier), importTest.toString().replace(".", "/")
                    + "/" + identifier.replace(".", "$"));
              }
            }
          }
        }
    
        return null;
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I get an entity manager in a normal java class? I tried
I've created a layout.xml file with the following XML, but I can't get the
Suppose I have a Singleton class (any class can get the instance): class data
Possible Duplicate: Can I get a reference to the 'owner' class during the init
I can't get PHP to recognize the ImageMagick (Imagick) class. Everything else works, the
How can I get at the Labels data from within my Task model? class
I simply can not get Visual Studio 2005 to find the System.Configuration.ConfigurationManager class. Here
I can't get past this issue I am having. Here's a simple example: class
How can I get the ConstructorInfo for a static constructor? public class MyClass {
I just can't get the ajax service to work. A simple class to $.get(http://google.com)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.