Blankj/AndroidUtilCode · error · UnsupportedOperationException

u can't instantiate me...

Error message

u can't instantiate me...

What it means

SizeUtils is a final static-only utility for dp/sp/px conversions. Its private constructor throws UnsupportedOperationException as an instantiation guard. Every method is static, so the class is meant to be used as a namespace, not constructed.

Source

Thrown at lib/utilcode/src/main/java/com/blankj/utilcode/util/SizeUtils.java:20

import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

/**
 * <pre>
 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2016/08/02
 *     desc  : utils about size
 * </pre>
 */
public final class SizeUtils {

    private SizeUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * Value of dp to value of px.
     *
     * @param dpValue The value of dp.
     * @return value of px
     */
    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Value of px to value of dp.
     *
     * @param pxValue The value of px.
     * @return value of dp

View on GitHub (pinned to 7b4caf9e54)

Solutions

  1. Call static methods: SizeUtils.dp2px(8) instead of constructing the class.
  2. Register a Gson InstanceCreator/Jackson mixin returning a sentinel to prevent reflective construction.
  3. Mock static methods with Mockito.mockStatic rather than instantiating.
  4. Preserve final + private constructor so tooling does not treat the class as instantiable.

Example fix

// before
SizeUtils su = gson.fromJson(json, SizeUtils.class);

// after
int px = SizeUtils.dp2px(8);
Defensive patterns

Strategy: validation

Validate before calling

if (Modifier.isFinal(SizeUtils.class.getModifiers())) {
  throw new IllegalStateException("SizeUtils is static-only; use dp2px etc.");
}

Prevention

When it happens

Trigger: Reflective instantiation (SizeUtils.class.getDeclaredConstructor().setAccessible(true).newInstance()) or transitive construction via Gson/Jackson, Mockito/PowerMock, Kotlin reflection, or a DI scan.

Common situations: Deserialization mapping a field to SizeUtils; mock frameworks instantiating utility classes; coverage tools; accidental `new SizeUtils()` after dropping the final modifier.

Related errors


AI-assisted analysis of Blankj/AndroidUtilCode@7b4caf9e54 (2026-08-14). Data as JSON: /api/errors/f4c85ec82566459d. Report an issue: GitHub.