简体   繁体   中英

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:

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

What is the best way to implement the same functionality in this scenario without loading the classToIgnoreName dynamically?

Thanks

It's the loading a class at runtime that's insecure - no matter which way you do this.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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