fix: provider now creates a new instance every time

This commit is contained in:
zaaarf 2023-08-27 00:10:36 +02:00
parent 3514ce5b3b
commit 539be77980
No known key found for this signature in database
GPG key ID: 6445A5CD15E5B40C

View file

@ -8,24 +8,37 @@ import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* The main class of the mapper library. It loads all the * The main class of the mapper library. It loads all the
* valid {@link IMapper}s and gets information from them. * valid {@link IMapper}s and gets information from them.
*/ */
public class MapperProvider { public class MapperProvider {
/**
* The static instance of the provider.
*/
private static MapperProvider INSTANCE = null; private static MapperProvider INSTANCE = null;
/**
* @return the static instance of the provider
*/
private static MapperProvider getInstance() { private static MapperProvider getInstance() {
return INSTANCE == null ? (INSTANCE = new MapperProvider()) : INSTANCE; return INSTANCE == null ? (INSTANCE = new MapperProvider()) : INSTANCE;
} }
private Set<IMapper> loadedMappers = null; /**
* A {@link Set} containing all the loaded mapper classes.
*/
private Set<Class<? extends IMapper>> loadedMappers = null;
/**
* Loads the mapper classes into a {@link Set}.
*/
private void loadMappers() { private void loadMappers() {
this.loadedMappers = new HashSet<>(); this.loadedMappers = new HashSet<>();
for(IMapper mapper: ServiceLoader.load(IMapper.class)) for(IMapper mapper: ServiceLoader.load(IMapper.class))
this.loadedMappers.add(mapper); this.loadedMappers.add(mapper.getClass());
if(this.loadedMappers.isEmpty()) if(this.loadedMappers.isEmpty())
throw new RuntimeException("Something went wrong: no mapper types were loaded successfully!"); throw new RuntimeException("Something went wrong: no mapper types were loaded successfully!");
} }
@ -41,7 +54,12 @@ public class MapperProvider {
if(getInstance().loadedMappers == null) if(getInstance().loadedMappers == null)
getInstance().loadMappers(); getInstance().loadMappers();
return getInstance().loadedMappers.stream() return getInstance().loadedMappers.stream()
.filter(m -> m.claim(data)) .flatMap(clazz -> {
try {
return Stream.of(clazz.newInstance());
} catch(ReflectiveOperationException ignored) {}
return Stream.empty();
}).filter(m -> m.claim(data))
.max(Comparator.comparingInt(IMapper::priority)) .max(Comparator.comparingInt(IMapper::priority))
.orElseThrow(InvalidResourceException::new); .orElseThrow(InvalidResourceException::new);
} }