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 7164001
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T13:59:48+00:00 2026-05-28T13:59:48+00:00

Given a Scope , is there a function that can generate a unique variable

  • 0

Given a Scope, is there a function that can generate a unique variable name such that a variable declaration for the unique name could be inserted in scope and the resulting source code/CompilationUnitTree would still compile?

  • 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-05-28T13:59:49+00:00Added an answer on May 28, 2026 at 1:59 pm

    I ended up writing my own utility function:

    import com.sun.source.tree.Scope;
    import javax.lang.model.element.Element;
    import javax.lang.model.element.ElementKind;
    import static javax.lang.model.element.ElementKind.*;
    import javax.lang.model.element.Name;
    import javax.lang.model.util.Elements;
    import org.apache.commons.lang3.StringUtils;
    
    public class ScopeUtils {
        private Elements elements;
    
        public ScopeUtils(Elements elements) {
            this.elements = elements;
        }
    
        public Name generateUniqueName(Scope scope, CharSequence prefixCs) {
            String prefix = prefixCs.toString(); // https://issues.apache.org/jira/browse/LANG-786
            int i = 0, j = 0;
    
            Scope enclosingScope;
            for (; scope != null && (enclosingScope = scope.getEnclosingScope()) != null; scope = enclosingScope) {
                for (Element e : scope.getLocalElements()) {
                    ElementKind kind = e.getKind();
                    String simpleName = e.getSimpleName().toString();
                    if (kind == LOCAL_VARIABLE ||
                            kind == PARAMETER ||
                            kind == EXCEPTION_PARAMETER ||
                            kind == TYPE_PARAMETER ||
    
                            kind == CLASS ||
                            kind == INTERFACE ||
                            kind == ENUM ||
                            kind == ANNOTATION_TYPE) {
                        if (StringUtils.startsWith(simpleName, prefix)) {
                            if (StringUtils.equals(simpleName, prefix)) {
                                i = Math.max(i, j + 1);
                            } else {
                                try {
                                    j = Math.max(j, Integer.parseInt(simpleName.subSequence(prefix.length(), simpleName.length()).toString(), 10));
                                } catch (NumberFormatException ex) {
                                    continue;
                                }
    
                                if (i > 0) {
                                    i = Math.max(i, j + 1);
                                }
                            }
                        }
                    } else {
                        assert kind == FIELD && (StringUtils.equals(simpleName, "super") || StringUtils.equals(simpleName, "this"));
                    }
                }
            }
    
            return elements.getName(i <= 0 ? prefix : String.format("%s%d", prefix, i));
        }
    }
    

    This was tested with the following test source file:

    package test.mytest;
    
    import org.slf4j.Logger/*INTERFACE*/;
    import org.slf4j.LoggerFactory/*CLASS*/;
    import test.mytest.MyEnum/*ENUM*/;
    import static test.mytest.MyEnum.*;
    
    @interface MyAnnotation/*ANNOTATION_TYPE*/ { }
    
    interface MyInterface/*INTERFACE*/ { }
    
    class MyClass/*CLASS*/ { }
    
    public class App/*CLASS*/ {
        private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
    
        private static final String STR1 = "test";
    
        private StringBuilder sb10 = new StringBuilder();
    
        //super/*FIELD*/
        //this/*FIELD*/
    
        public <T/*TYPE_PARAMETER*/> void test(T obj/*PARAMETER*/) {
            MyEnum e/*LOCAL_VARIABLE*/ = TEST1;
            switch (e) {
                case TEST1:
                    StringBuilder sb/*LOCAL_VARIABLE*/ = new StringBuilder();
                    StringBuilder sb1/*LOCAL_VARIABLE*/ = new StringBuilder();
                    obj = null;
                    if (obj == TEST1) { }
                    try {
                        obj.toString();
                    } catch (NullPointerException npe/*EXCEPTION_PARAMETER*/) {
                        StringBuilder sb3/*LOCAL_VARIABLE*/ = new StringBuilder();
                        final String str/*LOCAL_VARIABLE*/ = "hi!";
                        LOGGER.debug(STR1);
                    }
                default:
                    break;
            }
        }
    
        public static void main(String[] args) {
            new App().<String>test("test");
        }
    }
    

    where MyEnum is declared as:

    package test.mytest;
    
    public enum MyEnum {
        TEST1, TEST2;
    }
    

    The scope in question is the scope of the method invocation statement LOGGER.debug(STR1); within the catch block. Result: "sb4".

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a single function that can be created to tell whether a variable
Are there languages where the scope is defined in such a way that does
Given the following snippet of javascript in a scope: var x = 10; function
Given a Python object of any kind, is there an easy way to get
Given 2 rgb colors and a rectangular area, I'd like to generate a basic
Given the URL (single line): http://test.example.com/dir/subdir/file.html How can I extract the following parts using
is it possible to declare a variable length array with global scope in objective-c?
I have a script like so: test.ps1 param ( $name, $age ) function load-parameters()
I've written a function foreach that accepts a lambda function ala: void foreach(void (*p)(pNode))
Given that we have a script Option Explicit Class CClass Private m_date Private Sub

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.