Java SE API
ServiceLoader.Provider.type()
Obtain the provider type as defined by the provider contract. See official API for exceptions and overloads; Java 21-compatible example.
Formal Syntax & Structure
java syntaxjava
Class<? extends S> type()Return Value
Class<? extends S>
Obtain the provider type as defined by the provider contract.
Working Example
Example Snippetjava
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { public interface Formatter { String format(String input); } public static class Upper implements Formatter { public Upper() {} public String format(String input) { return input.toUpperCase(Locale.ROOT); } } public interface Missing {} // Only fixed, reviewed class names; no external JARs or user input. static void withProvider(boolean register, java.util.function.Consumer<ClassLoader> action) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-service-"); Path meta = dir.resolve("META-INF"); Path services = meta.resolve("services"); Path descriptor = services.resolve(Formatter.class.getName()); try { Files.createDirectories(services); if (register) Files.writeString(descriptor, Upper.class.getName() + "\n", StandardCharsets.UTF_8); try (URLClassLoader loader = new URLClassLoader(new URL[]{dir.toUri().toURL()}, Main.class.getClassLoader())) { action.accept(loader); } } finally { Files.deleteIfExists(descriptor); Files.deleteIfExists(services); Files.deleteIfExists(meta); Files.delete(dir); } } public static void main(String[] args) throws Throwable { withProvider(true, loader -> { ServiceLoader.Provider<Formatter> p = ServiceLoader.load(Formatter.class, loader).stream().findFirst().orElseThrow(); System.out.println(p.type().getSimpleName()); System.out.println(p.get().format("daily")); }); }}