我有一个静态引用变量
static IMail mailer = null;
我在 SearchManager 类的构造函数中为其赋值
public SearchManager(ILog logger, String basePath, String indexPath, String nwId, IMail mailer) {
this.logger = logger;
this.basePath = basePath;
this.indexPath = indexPath;
this.nwId = nwId;
this.mailer = mailer;
}
我在我的代码中使用邮件程序。此类的构造函数可能会被多次调用。所以我有一个疑问,每次调用构造函数时这个静态引用变量将如何表现。它是否只采用我第一次调用构造函数时传递的值,还是每次调用构造函数时都会采用不同的值?
最佳答案
首先,您不应将“this”关键字与静态变量一起使用。您可以执行以下操作(但不推荐)
public SearchManager(ILog logger, String basePath, String indexPath, String nwId, IMail mailerarg) {
this.logger = logger;
this.basePath = basePath;
this.indexPath = indexPath;
this.nwId = nwId;
mailer = mailerarg;
}
和是的,它是一个静态变量,每次创建类的新对象时都会发生变化。静态变量属于类而不是它的单个实例。因此,每当您更改它的值时,它都会反射(reflect)在所有相应的类对象中(所有对象都有其类信息)。
关于java - 静态引用变量的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17832250/