ServiceLoader class methods in Java

java.util.ServiceLoader

A facility to load implementations of a service. A service is a well-known interface or class for which zero, one, or many service providers exist.

Some methods of ServiceLoader class


equals(Object)This method indicates whether some other object is "equal to" this one.


findFirst()This method loads the first available service provider of this loader's service.


hashCode()This method returns a hash code value for the object.


iterator()This method returns an iterator to lazily load and instantiate the available providers of this loader's service.


load(Class)This method creates a new service loader for the given service type, using the current thread's context class loader.


load(Class, ClassLoader)This method creates a new service loader for the given service.


load(ModuleLayer, Class)This method creates a new service loader for the given service type to load service providers from modules in the given module layer and its ancestors.


loadInstalled(Class)This method creates a new service loader for the given service type, using the platform class loader.


reload()This method clears this loader's provider cache so that all providers will be reloaded.


spliterator()This method creates a Spliterator over the elements described by this Iterable.


stream()This method returns a stream to lazily load available providers of this loader'sservice.


toString()This method returns a string describing this service.


ServiceLoader toString() in Java

toString(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

String java.util.ServiceLoader.toString()

This method takes one argument. This method returns a string describing this service.

Parameters: NA

Returns: A descriptive string.

Exceptions: NA

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoadertoString {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        System.out.println(serviceLoader.toString());
    }

}

Output:

java.util.ServiceLoader[java.lang.String]


ServiceLoader stream() in Java

stream(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

Stream<Provider<K>> java.util.ServiceLoader.stream()

This method returns a stream to lazily load available providers of this loader'sservice.

Parameters: NA

Returns: A stream that lazily loads providers for this loader's service.

Exceptions: NA

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderstream {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        System.out.println(serviceLoader.stream());

    }

}

Output:

java.util.stream.ReferencePipeline$Head@3cd1f1c8


ServiceLoader spliterator() in Java

spliterator(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

Spliterator<K> java.lang.Iterable.spliterator()

This method creates a Spliterator over the elements described by this Iterable.

Parameters: NA

Returns:Spliterator over the elements described by this Iterable.

Exceptions: NA

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderspliterator {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        System.out.println(serviceLoader.spliterator());
    }

}

Output:

java.util.Spliterators$IteratorSpliterator@3a4afd8d


ServiceLoader reload() in Java

reload(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

void java.util.ServiceLoader.reload()

This method clears this loader's provider cache so that all providers will be reloaded.

Parameters: NA

Returns: NA

Exceptions: NA

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderreload {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        serviceLoader.reload();

        System.out.println("Reloaded Succesfully");

    }

}

Output:

Reloaded Succesfully


ServiceLoader loadInstalled(Class) in Java

loadInstalled(Class): This method is available in java.util.ServiceLoader class of Java.

Syntax:

<K> ServiceLoader<K> java.util.ServiceLoader.loadInstalled(Class<K> service)

This method takes one argument. This method creates a new service loader for the given service type, using the platform class loader.

Parameters: One parameter is required for this method.

service: The interface or abstract class representing the service.

Returns: A new service loader.

Throws:

ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service.

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderloadInstalled {
    public static void main(String[] args) {

        System.out.println(ServiceLoader.
loadInstalled(String.class));
    }

}

Output:

java.util.ServiceLoader[java.lang.String]


ServiceLoader load(ModuleLayer, Class) in Java

load(ModuleLayer, Class): This method is available in java.util.ServiceLoader class of Java.

Syntax:

<K> ServiceLoader<K> java.util.ServiceLoader.load(ModuleLayer layer, Class<K> service)

This method takes two arguments. This method creates a new service loader for the given service type to load service providers from modules in the given module layer and its ancestors.

Parameters: Two parameters are required for this method.

layer: The module layer.

service: The interface or abstract class representing the service.

Returns: A new service loader.

Throws:

ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service.

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderload3 {
    public static void main(String[] args) {

        ModuleLayer moduleLayer = ModuleLayer.boot();
        System.out.println(ServiceLoader.load(moduleLayer,
String.class));
    }

}

Output:

java.util.ServiceLoader[java.lang.String]


ServiceLoader load(Class, ClassLoader) in Java

load(Class, ClassLoader): This method is available in java.util.ServiceLoader class of Java.

Syntax:

<K> ServiceLoader<K> java.util.ServiceLoader.load(Class<K> service, ClassLoader loader)

This method takes two arguments. This method creates a new service loader for the given service. The service loader uses the given class loader as the starting point to locate service providers for the service.

Parameters: Two parameters are required for this method.

service: The interface or abstract class representing the service.

loader: The class loader to be used to load provider-configuration files and provider classes, or null if the system classloader (or, failing that, the bootstrap class loader) is to be used.

Returns: A new service loader.

Throws:

ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service.

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderload2 {
    public static void main(String[] args) {

        System.out.println(ServiceLoader.load(String.class,
new ClassLoader() {
        }));
    }

}

Output:

java.util.ServiceLoader[java.lang.String]


ServiceLoader load(Class) in Java

load(Class): This method is available in java.util.ServiceLoader class of Java.

Syntax:

<K> ServiceLoader<K> java.util.ServiceLoader.load(Class<K> service)

This method takes one argument. This method creates a new service loader for the given service type, using the current thread's context class loader.

Parameters: One parameter is required for this method.

service: The interface or abstract class representing the service.

Returns: A new service loader.

Throws:

ServiceConfigurationError - if the service type is not accessible to the caller or the caller is in an explicit module and its module descriptor does not declare that it uses service.

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderload {
    public static void main(String[] args) {

        System.out.println(ServiceLoader.load(String.class));
    }

}

Output:

java.util.ServiceLoader[java.lang.String]


ServiceLoader iterator() in Java

iterator(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

Iterator<String> java.util.ServiceLoader.iterator()

This method returns an iterator to lazily load and instantiate the available providers of this loader's service.

Parameters: NA

Returns: An iterator that lazily loads providers for this loader'sservice.

Exceptions: NA

Approach

Java

import java.util.Iterator;
import java.util.ServiceLoader;

public class ServiceLoaderiterator {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        Iterator<String> iterator = serviceLoader.iterator();

        System.out.println(iterator);

    }

}

Output:

java.util.ServiceLoader$3@3cd1f1c8


ServiceLoader hashCode() in Java

hashCode(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

int java.lang.Object.hashCode()

This method returns a hash code value for the object.

Parameters: NA

Returns: a hash code value for this object.

Exceptions: NA

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderhashCode {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        System.out.println(serviceLoader.hashCode());
    }

}

Output:

405662939


ServiceLoader findFirst() in Java

findFirst(): This method is available in java.util.ServiceLoader class of Java.

Syntax:

Optional<String> java.util.ServiceLoader.findFirst()

This method load the first available service provider of this loader's service.

Parameters: NA

Returns: The first service provider or empty Optional if no service providers are located.

Throws:

ServiceConfigurationError - If a provider class cannot be loaded.

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderfindFirst {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        System.out.println(serviceLoader.findFirst());
    }

}

Output:

Optional.empty


ServiceLoader equals(Object) in Java

equals(Object): This method is available in java.util.ServiceLoader class of Java.

Syntax:

boolean java.lang.Object.equals(Object obj)

This method takes one argument. This method indicates whether some other object is "equal to" this one.

Parameters: One parameter is required for this method.

obj: the reference object with which to compare.

Returns: true if this object is the same as the obj argument; false otherwise.

Exceptions: NA

Approach

Java

import java.util.ServiceLoader;

public class ServiceLoaderequals {
    public static void main(String[] args) {

        ServiceLoader<String> serviceLoader =
ServiceLoader.load(String.class);

        System.out.println(serviceLoader.equals(serviceLoader));
    }

}

Output:

true


Scanner class methods in Java Part -III

java.util.Scanner

A simple text scanner that can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.


Some methods of Scanner class.


nextByte(int)This method scans the next token of the input as a byte.


nextDouble()This method scans the next token of the input as a double.


nextFloat()This method scans the next token of the input as a float.


nextInt()This method scans the next token of the input as an int.


nextInt(int)This method scans the next token of the input as an int according to the specified radix.


nextLine()This method advances this scanner past the current line and returns the input that was skipped.


nextLong()This method scans the next token of the input as a long.


nextLong(int)This method scans the next token of the input as a long according to the specified radix.


nextShort()This method scans the next token of the input as a short.


nextShort(int)This method scans the next token of the input as a short according to the specified radix.

radix()This method returns this scanner's default radix.


remove()The remove operation is not supported by this implementation of Iterator.


reset()This method resets this scanner.


skip(Pattern)This method skips input that matches the specified pattern, ignoring delimiters.


skip(String)This method skips input that matches a pattern constructed from the specified string.


tokens()This method returns a stream of delimiter-separated tokens from this scanner.


toString()This method returns the string representation of this Scanner.


useDelimiter(Pattern)This method sets this scanner's delimiting pattern to the specified pattern.


useDelimiter(String)This method sets this scanner's delimiting pattern to a pattern constructed from the specified String.


useLocale(Locale)This method sets this scanner's locale to the specified locale.


useRadix(int)This method sets this scanner's default radix to the specified radix.


Some more methods of Scanner class -I


Some more methods of Scanner class -II


Scanner useRadix(int) in Java

useRadix(int): This method is available in java.util.Scanner class of Java.

Syntax:

Scanner java.util.Scanner.useRadix(int radix)

This method takes one argument. This method sets this scanner's default radix to the specified radix.

Parameters: One parameter is required for this method.

radix: The radix to use when scanning numbers.

Returns: this scanner.

Throws:

IllegalArgumentException - if the radix is out of range

Approach 1: When no exception

Java

import java.util.Scanner;

public class ScanneruseRadix {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        int radix = Character.MIN_RADIX;
        System.out.println(scanner.useRadix(radix));
        scanner.close();
    }
}

Output:

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\x{2c}][decimal separator=\x{2e}][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\QNaN\E][infinity string=\Q∞\E]



Approach 2: IllegalArgumentException 

Java

import java.util.Scanner;

public class ScanneruseRadix {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        int radix = Character.MIN_RADIX - 1;
        System.out.println(scanner.useRadix(radix));
        scanner.close();
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: radix:1 at java.base/java.util.Scanner.useRadix(Scanner.java:1353)


Scanner useLocale(Locale) in Java

useLocale(Locale): This method is available in java.util.Scanner class of Java.

Syntax:

Scanner java.util.Scanner.useLocale(Locale locale)

This method takes one argument. This method sets this scanner's locale to the specified locale.

Parameters: One parameter is required for this method.

locale: A string specifying the locale to use.

Returns: this scanner

Exceptions: NA

Approach

Java

import java.util.Locale;
import java.util.Scanner;

public class ScanneruseLocale {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        System.out.println(scanner.useLocale(Locale.US));
        scanner.close();
    }
}

Output:

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\x{2c}][decimal separator=\x{2e}][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\QNaN\E][infinity string=\Q∞\E]


Scanner useDelimiter(String) in Java

useDelimiter(String): This method is available in java.util.Scanner class of Java.

Syntax:

Scanner java.util.Scanner.useDelimiter(String pattern)

This method takes one argument. This method sets this scanner's delimiting pattern to a pattern constructed from the specified String.

Parameters: One parameter is required for this method.

pattern: A string specifying a delimiting pattern.

Returns: this scanner

Exceptions: NA

Approach

Java

import java.util.Scanner;

public class ScanneruseDelimiter2 {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        String pattern = "[a-z]";
        System.out.println(scanner.useDelimiter(pattern));
        scanner.close();
    }
}

Output:

java.util.Scanner[delimiters=[a-z]][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\x{2c}][decimal separator=\x{2e}][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\QNaN\E][infinity string=\Q∞\E]


Scanner useDelimiter(Pattern) in Java

useDelimiter(Pattern): This method is available in java.uti.Scanner class of ava.

Syntax:

Scanner java.util.Scanner.useDelimiter(Pattern pattern)

This method takes one argument. This method sets this scanner's delimiting pattern to the specified pattern.

Parameters: One parameter is required for this method.

pattern: A delimiting pattern.

Returns: this scanner

Approach

Java

import java.util.Scanner;
import java.util.regex.Pattern;

public class ScanneruseDelimiter {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        Pattern pattern = Pattern.compile("[a-z]");
        System.out.println(scanner.useDelimiter(pattern));
        scanner.close();
    }
}

Output:

java.util.Scanner[delimiters=[a-z]][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\x{2c}][decimal separator=\x{2e}][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\QNaN\E][infinity string=\Q∞\E]