Install4j:如何检查未提升的 RemoteCallable 运行

Install4j: how to check a RemoteCallable running unelevated

我的安装程序在安装过程中将一些信息存储在单例中 class。现在,我注意到在提升的操作中,单例 class 没有相同的实例。到目前为止,我还没有发现任何 workaround/solution 使它们共享同一个实例。所以,我决定确保如果有人想获得单例实例,他们必须从未提升的环境中调用。假设单身人士如下所示:

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);
    }
 }

但问题是,在某些情况下,我必须从提升的操作 class 中调用此添加报告。所以我在提升的操作中尝试了以下操作 class:

if (context.hasBeenElevated()) {
            return (Boolean) context.runUnelevated(new RemoteCallable() {
                @Override
                public Serializable execute() {
                    return getInstance(context).addReport(report);
                }
            });
        }

但是,正如您所看到的,如果我将相同的上下文对象从提升的操作 class 传递到 RemoteCallable class 所以,即使我是 运行 class 未提升,context.hasBeenElevated() 仍然 returns 为真。

除了上下文之外,还有其他方法可以检查海拔高度吗?如果您有任何其他更好的想法来防止任何人调用单例 getInstance() 方法,我会洗耳恭听。

我会使用不同的模式。将你的单例的所有方法设为静态,并使用 runUnelevated 调用包装数据访问:

public static boolean addReport(Report report, Context context) {
    context.runUnelevated(new RemoteCallable() {
        @Override
        public Serializable execute() {
             InvestigatorReport.reports.add(report);
             return null;
        }
    });
}

通过这种方式,您可以从提升和未提升的代码中调用方法,而无需在调用站点检查任何内容。