dimanche 9 janvier 2022

How to implement logic for annotation Java?

Assume I have class Laptop and its annotated with @ProcessorConstraint It is Java code without any frameworks. In Spring Framework you can implement custom annotation, then you create annotation handler class, that is implicitly handles your annotated fields/classes, etc. But how can I do that implicitely with Java only?

Now I have code, that checks "If class annotated - check field for nullable":

public static void main(String[] args) {
        Laptop laptop = new Laptop("Scissor keyboard");
        System.out.println(laptop);


        validateLaptop(laptop);
        laptop.setProcessor("Intel 7");
        validateLaptop(laptop);
    }

    private static void validateLaptop(Laptop laptop) {
        boolean annotationPresent = laptop.getClass().isAnnotationPresent(ProcessorConstraint.class);
        if (annotationPresent) {
            if (laptop.getProcessor() == null) {
                throw new RuntimeException("Processor must not be null");
            }
        }
    }

But it is explicitly and I have to check each object for that. What should I do to avoid this?





Aucun commentaire:

Enregistrer un commentaire