Skip to content

Add @ValidSubTypes #280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 17, 2025
Merged

Add @ValidSubTypes #280

merged 7 commits into from
Feb 17, 2025

Conversation

SentryMan
Copy link
Collaborator

@SentryMan SentryMan commented Feb 15, 2025

  • adds a new annotation to extract subtype info from a class
  • will generate a validator that uses instanceof (17) or pattern matching switch (21+) to redirect to the correct validator
  • add Jstachio (compile-time templating is pretty handy)

Given

@SubTypes({ByQuerySelector.class, ByIdSelector.class})
public interface EntitySelector {}

The following is generated

@Generated("avaje-validation-generator")
public class EntitySelectorValidationAdapter implements ValidationAdapter<EntitySelector> {

  private final ValidationAdapter<ByQuerySelector> subAdapter0;
  private final ValidationAdapter<ByIdSelector> subAdapter1;

  public EntitySelectorValidationAdapter(ValidationContext ctx) {
    this.subAdapter0 = ctx.adapter(ByQuerySelector.class);
    this.subAdapter1 = ctx.adapter(ByIdSelector.class);
  }

  @Override
  public boolean validate(EntitySelector value, ValidationRequest request, String field) {
    return switch(value) {
      case null -> true;
      case ByQuerySelector val -> subAdapter0.validate(val, request, field);
      case ByIdSelector val -> subAdapter1.validate(val, request, field);
      default -> true;
    };

  }
}

Fixes #279

@SentryMan SentryMan added the enhancement New feature or request label Feb 15, 2025
@SentryMan SentryMan requested a review from rbygrave February 15, 2025 01:33
@SentryMan SentryMan self-assigned this Feb 15, 2025
@SentryMan SentryMan enabled auto-merge (squash) February 15, 2025 01:36
@rbygrave
Copy link
Contributor

Pondering if @SubTypes should be more @ValidSubtypes in that people reading the code will have to look at the package to know that its related to validation per se.

@SentryMan
Copy link
Collaborator Author

Never said I was great at naming, feel free to change

@SentryMan SentryMan changed the title Add @SubTypes Add @ValidSubTypes Feb 16, 2025
@SentryMan SentryMan merged commit d96c42f into avaje:main Feb 17, 2025
6 checks passed
@rbygrave rbygrave added this to the 2.8 milestone Feb 17, 2025
@SentryMan SentryMan deleted the subtypes branch February 17, 2025 15:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Validation of actual type stored in a field
2 participants