Safeguard
Application Security•

CWE-1063 Creating a Class Instance in a Static Code Block

Building objects inside a static initializer does work before it is needed. CWE-1063 explains the performance risk and a lazy alternative.

Safeguard Security Team
2 min read

CWE-1063 covers a static code block that creates an instance of a class. MITRE describes the pattern as a storable or member data element initialized in a block declared static. It applies to Java, C# and other languages with static initializers.

How it happens

A static block runs when the class loads, whether or not the object is ever used. If the object is expensive, such as one that opens a connection or reads a file, every load pays the cost.

// Pattern to avoid: work done at class load time
class Reports {
    static final Formatter FORMATTER;
    static {
        FORMATTER = new Formatter(loadTemplates());
    }
}
// Better: create it when first needed
class Reports {
    private static class Holder {
        static final Formatter FORMATTER = new Formatter(loadTemplates());
    }
    static Formatter formatter() { return Holder.FORMATTER; }
}

What an attacker gains

MITRE lists reduced performance, because initialization happens before it is needed. If an attacker can reach the code, the slowdown "might introduce a vulnerability."

How to find it

The record lists no detection methods. Search for static { blocks and check what each one builds.

How to fix it

Defer creation until first use, keep static blocks cheap, and avoid doing input or output work during class loading.

Quick check

Why is class load time a bad place for heavy work?

It runs whether or not the object is ever used, so the cost is paid up front every time.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.