Register custom annotation in Java

66 views Asked by At

I’m working on a project using only the Javalin framework and google Guice inject.

I’m having a hard time recording a custom annotation in the project to be used by any class

I created a custom annotation to make a regex in a string of a class

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Regex {}

Here is the implementation for this annotation

public class RegexProcessor {

    public static void process(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Regex.class) && field.getType().equals(String.class)) {
                try {
                    field.setAccessible(true);
                    String originalValue = (String) field.get(obj);
                    if (originalValue != null) {
                        String result = originalValue .replaceAll("\\s+","");
                        field.set(obj, result);
                    }
                } catch (IllegalAccessException e) {
                    log.error("error: ", e);
                }
            }
        }
    }
}

To use my note, I have to do this

ExampleClass example = new ExampleClass(" Hollo Word ");
RegexProcessor.process(example); // I want to have to do it every time
System.out.println(example.getText());

Class

class ExampleClass {
        @Regex
        private String text;

        public ExampleClass(String text) {
            this.text = text;
        }

        public String getText() {
            return text;
        }

        // Other fields and methods...
    }

If anyone has any example of how I can achieve this

0

There are 0 answers