Blankj/AndroidUtilCode · error · UnsupportedOperationException

u can't instantiate me...

Error message

u can't instantiate me...

What it means

TouchUtils is a final static-only utility for attaching touch-direction listeners to Views. Its private constructor throws UnsupportedOperationException to block instantiation. All public methods (setOnTouchListener, etc.) are static and direction constants are class-level.

Source

Thrown at lib/utilcode/src/main/java/com/blankj/utilcode/util/TouchUtils.java:35

 *     time  : 2019/08/26
 *     desc  : utils about touch
 * </pre>
 */
public class TouchUtils {

    public static final int UNKNOWN = 0;
    public static final int LEFT    = 1;
    public static final int UP      = 2;
    public static final int RIGHT   = 4;
    public static final int DOWN    = 8;

    @IntDef({LEFT, UP, RIGHT, DOWN})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Direction {
    }

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

    public static void setOnTouchListener(final View v, final OnTouchUtilsListener listener) {
        if (v == null || listener == null) {
            return;
        }
        v.setOnTouchListener(listener);
    }

    public static abstract class OnTouchUtilsListener implements View.OnTouchListener {

        private static final int STATE_DOWN = 0;
        private static final int STATE_MOVE = 1;
        private static final int STATE_STOP = 2;

        private static final int MIN_TAP_TIME = 1000;

        private int touchSlop;

View on GitHub (pinned to 7b4caf9e54)

Solutions

  1. Call the static API: TouchUtils.setOnTouchListener(view, listener) instead of constructing.
  2. Register a Gson InstanceCreator / Jackson mixin returning a sentinel so the constructor is not invoked.
  3. Use Mockito.mockStatic for mocking rather than instantiation.
  4. Keep the class final with a private constructor.

Example fix

// before
TouchUtils tu = new TouchUtils();

// after
TouchUtils.setOnTouchListener(view, listener);
Defensive patterns

Strategy: validation

Validate before calling

if (Modifier.isFinal(TouchUtils.class.getModifiers())) {
  throw new IllegalStateException("TouchUtils is static-only.");
}

Prevention

When it happens

Trigger: Reflective instantiation via TouchUtils.class.getDeclaredConstructor().setAccessible(true).newInstance(), or transitively through Gson/Jackson deserialization, Mockito/PowerMock, Kotlin reflection, or a DI scan.

Common situations: Serialization frameworks binding a field to TouchUtils; mock frameworks in tests; coverage tooling; accidental `new TouchUtils()` after weakening modifiers.

Related errors


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