简体   繁体   English

在 Java 中动态加载 class 的替代方法

[英]Alternative to loading class dynamically in Java

I have the following method:我有以下方法:

private static Class<?> classForName(final String classNameToIgnore) {
    try {
        return TypeAnyHelper.class.getClassLoader().loadClass(classNameToIgnore);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

This has been flagged as potentially insecure as we are dynamically loading a class at runtime:这已被标记为潜在不安全,因为我们在运行时动态加载 class:

return TypeAnyHelper.class.getClassLoader().loadClass(classNameToIgnore);

What is the best way to implement the same functionality in this scenario without loading the classToIgnoreName dynamically?在这种情况下无需动态加载 classToIgnoreName 即可实现相同功能的最佳方法是什么?

Thanks谢谢

It's the loading a class at runtime that's insecure - no matter which way you do this.在运行时加载 class 是不安全的——无论您采用哪种方式。

Technically, you could embed a groovy interpreter and execute runtime code that way - this might get you around the warning that you're mentioning, but you'd be open to exactly the same vulnerabilities: You're running code that potentially has not been vetted to run on a server or in the environment that you're running.从技术上讲,您可以嵌入一个 groovy 解释器并以这种方式执行运行时代码 - 这可能会让您绕过您提到的警告,但您会面临完全相同的漏洞:您正在运行可能尚未运行的代码经过审查可以在服务器上或您正在运行的环境中运行。

As you ask for an alternative in this scenario : We don't know your scenario.当您在这种情况下要求替代方案时:我们不知道您的情况。 Some static warnings make you think twice about the technique used.一些 static 警告让您对所使用的技术三思而后行。 If it is mandatory to use this technique, because you're implementing that kind of software : Ignore it, and document why you do so.如果必须使用此技术,因为您正在实施那种软件:请忽略它,并记录您这样做的原因。

If you truly need an alternative, I'd consider this question a xy-Problem and you should state your underlying business problem rather than the implementation that you already chose - because it might be the wrong choice for an implementation in the first place.如果你真的需要一个替代方案,我会认为这个问题是一个xy 问题,你应该 state 你的潜在业务问题而不是你已经选择的实现 - 因为它可能首先是错误的实现选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM