Skip to content

Instantly share code, notes, and snippets.

@Konicai
Created August 8, 2022 22:06
Show Gist options
  • Select an option

  • Save Konicai/cb17ecc4534d27b9746827e01b980d12 to your computer and use it in GitHub Desktop.

Select an option

Save Konicai/cb17ecc4534d27b9746827e01b980d12 to your computer and use it in GitHub Desktop.
package dev.kejona.crossplatforms.serialize;
import io.leangen.geantyref.GenericTypeReflector;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.objectmapping.meta.Constraint;
import org.spongepowered.configurate.objectmapping.meta.PostProcessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
public class ConstraintPostProcessor<A extends Annotation> implements PostProcessor.Factory {
private final Class<A> annotationType;
private final Class<?> valueType;
private final Constraint.Factory<A, ?> constraintFactory;
public <V> ConstraintPostProcessor(Class<A> annotation, Class<V> valueType, Constraint.Factory<A, V> constraint) {
this.annotationType = annotation;
this.valueType = valueType;
this.constraintFactory = constraint;
}
public ConstraintPostProcessor(Class<A> annotation, Constraint.Factory<A, Object> constraint) {
this.annotationType = annotation;
this.valueType = Object.class;
this.constraintFactory = constraint;
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @Nullable PostProcessor createProcessor(Type type) {
final Class<?> instanceType = GenericTypeReflector.erase(type);
if (valueType.isAssignableFrom(instanceType)) {
final A annotation = instanceType.getAnnotation(annotationType);
if (annotation != null) {
final Constraint constraint = constraintFactory.make(annotation, instanceType);
return constraint::validate;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment