kill-9
kill-9

Reputation: 104

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

Upvotes: 0

Views: 63

Answers (1)

Olaf Kock
Olaf Kock

Reputation: 48122

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.

Upvotes: 1

Related Questions