jeudi 22 juillet 2021

Cannot get Annotation with Reflection Java

I tried to put annotation to method and the retrieve the data inside it, but when I debug the code, I cannot get any annotations present.

This is may DatabaseSeederImpl, simple class that calls different services to seed data into database.

@Override
    public void seed() {
        seedData(SeedUserDto.class, userService);
        seedData(SeedCategoryDto.class, categoryService);
        seedData(SeedProductDto.class, productService);
    }

    private <S> void seedData(Class<?> dtoType, S service) {
        Arrays.stream(service.getClass().getDeclaredMethods())
                .filter(method -> method.isAnnotationPresent(Seed.class))
                .forEach(method -> {
                    try {
                        String fileName = method.getDeclaredAnnotation(Seed.class).fileName();
                        method.invoke(service, gson.fromJson(readJson(fileName), dtoType.arrayType()));
                    } catch (IllegalAccessException | InvocationTargetException | IOException e) {
                        e.printStackTrace();
                    }
                });
    }

This is my annotation which targets methods and its retention policy is set to runtime.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Seed {
    String fileName();
}

And in my services, I set this annotation with proper value.

@Override
@Transactional
@Seed(fileName = "categories.json")
public void seedCategories(SeedCategoryDto[] categoryDtos) {
    if (categoryRepository.count() == 0) {
        List<Category> categories = Arrays.stream(categoryDtos)
                .filter(dataValidator::isValid)
                .map(dto -> modelMapper.map(dto, Category.class))
                .collect(Collectors.toList());

        categoryRepository.saveAll(categories);
    }
}

And this is my directory tree.

Directory Tree





Aucun commentaire:

Enregistrer un commentaire