有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何知道变量的初始化位置

我们在应用程序中使用J2EE和Spring。 我的应用程序中有以下代码:

public class StreamThread extends Thread implements Constants{
{
    private Set<String> allsymbolSet= new HashSet<String>();
    boolean switchTab(String tab) throws Exception 
    {
        if (somecondition) {
            SymbolsSet = allsymbolSet;
        }  
    }
}

这个问题可能很有趣,但我仍在尝试我的运气。 我不知道allsymbolSet是如何设置的

如何知道值allsymbolSet在何处初始化? 这个allsymbolSet不是静态的或恒定的;它因用户而异

Spring中有这样的配置吗


共 (2) 个答案

  1. # 1 楼答案

    设置在哪里

    private Set<String> allsymbolSet= new HashSet<String>(); // Right here.
    

    何时设置When the instance is created。根据Java语言规范:

    If a field declarator contains a variable initializer, then it has the semantics of an assignment (§15.26) to the declared variable, and: ...

    • ...If the declarator is for an instance variable (that is, a field that is not static), then the variable initializer is evaluated and the assignment performed each time an instance of the class is created (§12.5).

    它以这种方式工作的原因是您只处理具有allSymbolSet的POJO。它不是通过XML或构造函数参数连接的,也不是@Autowired(这将是奇怪的),因此每当创建StreamThread的实例时,该实例变量也是如此

  2. # 2 楼答案

    你的问题真的很不清楚。我试着猜你想问什么

    public class Foo {
    {
        private Set<String> bar = new HashSet<String>();   // 1
    
        public void doSomething() {
            assert bar != null;  //2
        }
    }
    

    在第1行,显然是bar已初始化(使用new HashSet<>())。假设第2行中的断言没有失败,这意味着第1行是预先执行的。这就是你要问的吗

    When will the initialization of line 1 be executed?

    如果是,那么您可以简单地将其视为:在超级类构造函数调用之后,字段初始化和初始化块的逻辑将自动“复制”到所有构造函数的开头

    以此为例:

    public class Foo {
    {
        private Set<String> bar = new HashSet<String>();   // 1
    
        {   // initializer
            bar.add("BAR");
        }
    
        public Foo() {
           someInitLogic();
        }
    
        public void doSomething() {
            assert bar != null;  //2
        }
    }
    

    编译器将为您生成代码,使其看起来像:

    public class Foo {
    {
        private Set<String> bar;
    
    
        public Foo() {
            super();      // auto-generated invocation of superclass ctor
            bar = new HashSet<String>();   // field initialization and 
            bar.add("BAR");                // initializers
    
            someInitLogic();
        }
    
        public void doSomething() {
            assert bar != null;  //2
        }
    }