我的安装程序在安装过程中将一些信息存储在单例类中。现在,我注意到在提升的操作中,单例类没有相同的实例。到目前为止,我还没有找到任何解决方法/解决方案,以便它们共享相同的实例。因此,我决定确保如果有人想要获取单例实例,他们必须从未提升的环境中调用。假设单例如下所示:
public class InvestigatorReport {
private final List<Report> reports = new ArrayList<>();
private final static InvestigatorReport INSTANCE = new InvestigatorReport();
private InvestigatorReport() {
MyLogger.logInfo(getClass(), "initiating...");
}
public static InvestigatorReport getInstance(Context context) {
if (context.hasBeenElevated()) {
throw new IllegalAccessError(
"this method must be called unelevated!");
}
return INSTANCE;
}
private boolean addReport(Report report) {
return reports.add(report);
}
}
但问题是,在某些情况下,我必须从提升的操作类中调用此添加报告。因此,我在我的高级 Action 类(class)中尝试了以下操作:
if (context.hasBeenElevated()) {
return (Boolean) context.runUnelevated(new RemoteCallable() {
@Override
public Serializable execute() {
return getInstance(context).addReport(report);
}
});
}
但是,正如您所看到的,如果我将相同的上下文对象从提升的操作类传递到 RemoteCallable
类,那么即使我运行未提升的类,context.hasBeenElevated()
仍然返回 true。
除了上下文之外,还有其他方法可以检查海拔高度吗?如果您有任何其他更好的想法来防止任何人调用单例 getInstance()
方法,我洗耳恭听。
最佳答案
我会使用不同的模式。将单例的所有方法设为静态,并使用 runUnelelevated
调用包装数据访问:
public static boolean addReport(Report report, Context context) {
context.runUnelevated(new RemoteCallable() {
@Override
public Serializable execute() {
InvestigatorReport.reports.add(report);
return null;
}
});
}
通过这种方式,您可以从提升的代码和未提升的代码中调用方法,而无需在调用站点检查任何内容。
关于java - Install4j:如何检查 RemoteCallable 是否未提升运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48425179/