'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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Olaf Kock