-1

im working in java project where i have a map of exception that will be used in spring retryTemplate. this is my Map :

Map<Class<? extends Throwable>, Boolean> exceptionMap = new HashMap<>();

// list exception to trigger retry
exceptionMap.put(IllegalArgumentException.class, true);
exceptionMap.put(TimeoutException.class, true);
exceptionMap.put(RuntimeException.class, true);
exceptionMap.put(TopicAuthorizationException.class, true);
exceptionMap.put(MemberIdRequiredException.class, true);

my issue is that i don't know the exact exception class so i want to load the list dynamically from properties file. this is my property :

myapp.exception.class=TimeoutException,RuntimeException,TopicAuthorizationException,MemberIdRequiredException

i load my property in my class :

@Value("${myapp.exception.class}")
private String myclassesList;

do you have any idea please on how i can get the values from my properties and put each element in my Map.

Thanks in advance.

Regards

James
  • 1,190
  • 5
  • 27
  • 52
  • example with list https://stackoverflow.com/a/12580260/7505687 how about map all values will be 'true' on properties? about key and values you could check this https://stackoverflow.com/a/50979119/7505687 – Dilermando Lima Oct 13 '21 at 14:13

1 Answers1

0

The valid name should be (ex with Runtime and IllegalArgument ):

java.lang.RuntimeException, java.lang.IllegalArgumentException

Then you can use below method to convert name to Class.

private Class<?> getClass(String name) {
        try {
            return Class.forName(name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

Here is the way to convert list name to map:

List<String> exList = Arrays.asList(RuntimeException.class.getName(), IllegalArgumentException.class.getName());
Map<Class<?>, Boolean> map = exList.stream().map(name -> getClass(name)).filter(e -> !Objects.isNull(e))
                .collect(Collectors.toMap(e -> e, e -> true));
Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11