Java SE API
ServiceLoader.findFirst()
Return first available service instance or empty Optional. See official API for exceptions and overloads; Java 21-compatible example.
Formal Syntax & Structure
java syntaxjava
Optional<S> findFirst()Return Value
Optional<S>
Return first available service instance or empty Optional.
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(false, loader -> { Optional<Formatter> f = ServiceLoader.load(Formatter.class, loader).findFirst(); System.out.println(f.map(x -> x.format("invoice")).orElse("no formatter")); }); }}