Skip to content

Commit

Permalink
Load services through class loader of caller
Browse files Browse the repository at this point in the history
The caller supplies the service type using which `JavaSourceFile#service()` can instantiate a service of the desired type and also make sure it gets loaded using the corresponding class loader.
  • Loading branch information
knutwannheden committed Nov 20, 2023
1 parent 31d9eaa commit a19cc9c
Showing 1 changed file with 12 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.openrewrite.java.service.AutoFormatService;
import org.openrewrite.java.service.ImportService;

import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.util.List;

Expand Down Expand Up @@ -55,14 +56,19 @@ public interface JavaSourceFile extends J {
SourceFile withSourcePath(Path path);

@Incubating(since = "8.2.0")
@SuppressWarnings("unchecked")
default <S> S service(Class<S> service) {
if (ImportService.class.getName().equals(service.getName())) {
return (S) new ImportService();
} else if (AutoFormatService.class.getName().equals(service.getName())) {
return (S) new AutoFormatService();
try {
// use name indirection due to possibility of multiple class loaders being used
if (ImportService.class.getName().equals(service.getName())) {
return service.getConstructor().newInstance();
} else if (AutoFormatService.class.getName().equals(service.getName())) {
return service.getConstructor().newInstance();
} else {
throw new UnsupportedOperationException("Service " + service + " not supported");
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
throw new UnsupportedOperationException("Service " + service + " not supported");
}

interface Padding {
Expand Down

0 comments on commit a19cc9c

Please sign in to comment.