Skip to content

Refactor SqlTestContainer discovery to use Class.asSubclass() for better type safety #33261

@CarlosJPantoja

Description

@CarlosJPantoja
Overview of the feature request

Currently, the generator produces code for SqlTestContainer initialization that relies on a manual unchecked cast:

Class<? extends SqlTestContainer> containerClass = (Class<? extends SqlTestContainer>) Class.forName(...);

The proposal is to refactor this in the EJS templates to use the asSubclass() method from the Java Reflection API:

Class<? extends SqlTestContainer> containerClass = Class.forName(...).asSubclass(SqlTestContainer.class);

This change should be applied to the EJS templates responsible for generating the database test configuration.

Motivation for or Use Case

The current implementation triggers "unchecked cast" warnings and is less robust. Using .asSubclass(SqlTestContainer.class):

  1. Improves Type Safety: It performs a runtime check to ensure the class actually extends SqlTestContainer, throwing a ClassCastException immediately if it doesn't, which is easier to debug.
  2. Cleaner Code: It follows modern Java best practices for reflection, removing the need for manual casting and @SuppressWarnings("unchecked") if it were present.
  3. Maintainability: It aligns the generated code with higher quality standards for Java development.
Related issues or PR

I have searched existing issues and PRs and didn't find a previous proposal for this specific refactor in the TestContainers initialization logic.

  • Checking this box is mandatory (this is just to show you read everything)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions