package icse.demo.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 * Class demonstrating the use of the Reflection API in Java. Based on
 * https://docs.oracle.com/javase/tutorial/reflect/member/index.html and
 * https://docs.oracle.com/javase/tutorial/reflect/class/index.html
 */
public class JavaReflectionDemo
{

    /**
     * This main method demonstrates how to use the Reflection API to query information about classes and their members,
     * change field values, and invoke methods and constructors, all at runtime.
     * 
     * @param args
     *            command line arguments (not used)
     */
    public static void main(String[] args)
    {
        List<String> authors = new ArrayList<>();
        authors.add("Robert Jordan");
        Book book = new Book("A Memory of Light", authors);

        queryClassInformation("icse.demo.reflection.Book");
        getAndChangeField(book);
        invokeMethod(book);
        invokeConstructor();
    }

    /**
     * Shows information about an unknown target class.
     * 
     * If the argument is a String, it is expected to be the fully qualified name of the class (e.g.,
     * "icse.demo.reflection.Book"). If the argument is a Class object, the method shows information about that class.
     * If it is an instance of any other class, the method shows information about the run-time class of that object.
     * 
     * @param unknown
     *            the target class.
     */
    public static void queryClassInformation(Object unknown)
    {
        Class<?> unknownClass;
        if (unknown instanceof String)
        {
            try
            {
                unknownClass = Class.forName((String) unknown);
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
                return;
            }
        }
        else if (unknown instanceof Class)
        {
            unknownClass = (Class<?>) unknown;
        }
        else
        {
            unknownClass = unknown.getClass();
        }
        System.out.println("Information about class: " + unknownClass.getName());

        System.out.println("Fields:");
        for (Field field : unknownClass.getDeclaredFields()
        {
            System.out.println("  " + field.toGenericString());
        }

        System.out.println("Methods:");
        for (Method method : unknownClass.getDeclaredMethods()
        {
            System.out.println("  " + method.toGenericString());
        }

        System.out.println("Constructors:");
        for (Constructor<?> constructor : unknownClass.getDeclaredConstructors()
        {
            System.out.println("  " + constructor.toGenericString());
        }
        System.out.println();
    }

    /**
     * Accesses and modifies the private fields (title and authors) of a book using reflection.
     * 
     * @param book
     *            the book object to modify
     */
    public static void getAndChangeField(Book book)
    {
        try
        {
            Class<?> bookClass = Book.class;
            Field titleField = bookClass.getDeclaredField("title");
            titleField.setAccessible(true);
            titleField.set(book, "The Wheel of Time: A Memory of Light");

            Field authorField = bookClass.getDeclaredField("authors");
            authorField.setAccessible(true);
            List<String> authors = (List<String>) authorField.get(book);
            authors.add("Brandon Sanderson");

            System.out.println(book);
        }
        catch (ReflectiveOperationException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Invoke a private instance method of the book object.
     * 
     * @param book
     *            object for which to invoke the private method
     */
    public static void invokeMethod(Book book)
    {
        try
        {
            Class<?> bookClass = Book.class;
            Method method = bookClass.getDeclaredMethod("formatAuthors", boolean.class);
            method.setAccessible(true);
            String returnValue = (String) method.invoke(book, true);
            System.out.println(returnValue);
        }
        catch (ReflectiveOperationException e)
        {
            e.printStackTrace();
        }
    }

    public static void invokeConstructor()
    {
        try
        {
            Class<Book> bookClass = Book.class;
            Constructor<Book> constructor = bookClass.getDeclaredConstructor(String.class, List.class);
            Book newBook = constructor.newInstance("The Way of Kings", List.of("Brandon Sanderson"));
            System.out.println(newBook);
        }
        catch (ReflectiveOperationException e)
        {
            e.printStackTrace();
        }
    }

}

/**
 * A simple class representing a book with a title and a list of authors.
 */
class Book
{

    private String title;
    private List<String> authors;

    public Book(String title, List<String> authors)
    {
        this.title = title;
        this.authors = authors;
    }

    private String formatAuthors(boolean sorted)
    {
        List<String> copy = new ArrayList<>(authors);
        if (sorted)
        {
            Collections.sort(copy);
        }
        switch (copy.size())
        {
        case 0:
            return "unknown authors";
        case 1:
            return copy.get(0);
        case 2:
            return copy.get(0) + " and " + copy.get(1);
        default:
            String list = "";
            for (int i = 0; i < copy.size(); i++)
            {
                if (i > 0)
                {
                    list += ", ";
                }
                if (i == copy.size() - 1)
                {
                    list += "and ";
                }
                list += copy.get(i);
            }
            return list;
        }
    }

    @Override
    public String toString()
    {
        return title + " by " + formatAuthors(false);
    }
}

Official API Reference

Constructs an empty list with an initial capacity of ten.

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

Appends the specified element to the end of this list (optional operation).

Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

Specified by:
add in interface Collection<E>
Parameters:
e - element to be appended to this list
Returns:
true (as specified by Collection.add(E))
Throws:
UnsupportedOperationException - if the add operation is not supported by this list
ClassCastException - if the class of the specified element prevents it from being added to this list
NullPointerException - if the specified element is null and this list does not permit null elements
IllegalArgumentException - if some property of this element prevents it from being added to this list

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Since:
1.0
See Also:
Class

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Since:
1.0
See Also:
Class

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a class literal. For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form

Official API Reference

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Since:
1.0
See Also:
Class

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a class literal. For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form

Official API Reference

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:
 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
 
This example was produced by running the program:
 class MyClass {
     public static void main(String[] args) {
         crunch(null);
     }
     static void crunch(int[] a) {
         mash(a);
     }
     static void mash(int[] b) {
         System.out.println(b[0]);
     }
 }
 
The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
 HighLevelException: MidLevelException: LowLevelException
         at Junk.a(Junk.java:13)
         at Junk.main(Junk.java:4)
 Caused by: MidLevelException: LowLevelException
         at Junk.c(Junk.java:23)
         at Junk.b(Junk.java:17)
         at Junk.a(Junk.java:11)
         ... 1 more
 Caused by: LowLevelException
         at Junk.e(Junk.java:30)
         at Junk.d(Junk.java:27)
         at Junk.c(Junk.java:21)
         ... 3 more
 
Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
 public class Junk {
     public static void main(String args[]) {
         try {
             a();
         } catch(HighLevelException e) {
             e.printStackTrace();
         }
     }
     static void a() throws HighLevelException {
         try {
             b();
         } catch(MidLevelException e) {
             throw new HighLevelException(e);
         }
     }
     static void b() throws MidLevelException {
         c();
     }
     static void c() throws MidLevelException {
         try {
             d();
         } catch(LowLevelException e) {
             throw new MidLevelException(e);
         }
     }
     static void d() throws LowLevelException {
        e();
     }
     static void e() throws LowLevelException {
         throw new LowLevelException();
     }
 }

 class HighLevelException extends Exception {
     HighLevelException(Throwable cause) { super(cause); }
 }

 class MidLevelException extends Exception {
     MidLevelException(Throwable cause)  { super(cause); }
 }

 class LowLevelException extends Exception {
 }
 
As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the try-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
 Exception in thread "main" java.lang.Exception: Something happened
  at Foo.bar(Foo.java:10)
  at Foo.main(Foo.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 0
          at Resource.close(Resource.java:26)
          at Foo.bar(Foo.java:9)
          ... 1 more
 
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

 Exception in thread "main" java.lang.Exception: Main block
  at Foo3.main(Foo3.java:7)
  Suppressed: Resource$CloseFailException: Resource ID = 2
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 1
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
 Caused by: java.lang.Exception: I did it
  at Foo3.main(Foo3.java:8)
 
Likewise, a suppressed exception can have a cause:
 Exception in thread "main" java.lang.Exception: Main block
  at Foo4.main(Foo4.java:6)
  Suppressed: Resource2$CloseFailException: Resource ID = 1
          at Resource2.close(Resource2.java:20)
          at Foo4.main(Foo4.java:5)
  Caused by: java.lang.Exception: Rats, you caught me
          at Resource2$CloseFailException.<init>(Resource2.java:45)
          ... 2 more
 

Official API Reference

All Implemented Interfaces:
Serializable
Thrown when an application tries to load in a class through its string name using:

but no definition for the class with the specified name could be found.

As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "optional exception that was raised while loading the class" that may be provided at construction time and accessed via the getException() method is now known as the cause, and may be accessed via the Throwable.getCause() method, as well as the aforementioned "legacy method."

Since:
1.0
See Also:
Class.forName(java.lang.String), ClassLoader.findSystemClass(java.lang.String), ClassLoader.loadClass(java.lang.String, boolean), Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a class literal. For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form

Official API Reference

Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to: Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class.

For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread:

Class t = Class.forName("java.lang.Thread")

A call to forName("X") causes the class named X to be initialized.

Parameters:
className - the fully qualified name of the desired class.
Returns:
the Class object for the class with the specified name.
Throws:
LinkageError - if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method fails
ClassNotFoundException - if the class cannot be located
See Java Language Specification:
12.2 Loading of Classes and Interfaces
12.3 Linking of Classes and Interfaces
12.4 Initialization of Classes and Interfaces

Official API Reference

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object.

If this Class object represents a class or interface, not an array class, then:

If this Class object represents an array class, then the result is a string consisting of one or more '[' characters representing the depth of the array nesting, followed by the element type as encoded using the following table:

Element types and encodings
Element Type Encoding
boolean Z
byte B
char C
class or interface with binary name N LN;
double D
float F
int I
long J
short S

If this Class object represents a primitive type or void, then the result is a string with the same spelling as the Java language keyword which corresponds to the primitive type or void.

Examples:

 String.class.getName()
     returns "java.lang.String"
 byte.class.getName()
     returns "byte"
 (new Object[3]).getClass().getName()
     returns "[Ljava.lang.Object;"
 (new int[3][4][5][6][7][8][9]).getClass().getName()
     returns "[[[[[[[I"
 

Returns:
the name of the class, interface, or other entity represented by this Class object.
See Java Language Specification:
13.1 The Form of a Binary

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

All Implemented Interfaces:
AnnotatedElement, Member
A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.

A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getFields(), Class.getField(String), Class.getDeclaredFields(), Class.getDeclaredField(String)

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

All Implemented Interfaces:
AnnotatedElement, GenericDeclaration, Member
A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).

A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getMethods(), Class.getMethod(String, Class[]), Class.getDeclaredMethods(), Class.getDeclaredMethod(String, Class[])

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

Type Parameters:
T - the class in which the constructor is declared
All Implemented Interfaces:
AnnotatedElement, GenericDeclaration, Member
Constructor provides information about, and access to, a single constructor for a class.

Constructor permits widening conversions to occur when matching the actual parameters to newInstance() with the underlying constructor's formal parameters, but throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getConstructors(), Class.getConstructor(Class[]), Class.getDeclaredConstructors()

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

Official API Reference

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Since:
1.0
See Also:
Class

Official API Reference

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:
 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
 
This example was produced by running the program:
 class MyClass {
     public static void main(String[] args) {
         crunch(null);
     }
     static void crunch(int[] a) {
         mash(a);
     }
     static void mash(int[] b) {
         System.out.println(b[0]);
     }
 }
 
The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
 HighLevelException: MidLevelException: LowLevelException
         at Junk.a(Junk.java:13)
         at Junk.main(Junk.java:4)
 Caused by: MidLevelException: LowLevelException
         at Junk.c(Junk.java:23)
         at Junk.b(Junk.java:17)
         at Junk.a(Junk.java:11)
         ... 1 more
 Caused by: LowLevelException
         at Junk.e(Junk.java:30)
         at Junk.d(Junk.java:27)
         at Junk.c(Junk.java:21)
         ... 3 more
 
Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
 public class Junk {
     public static void main(String args[]) {
         try {
             a();
         } catch(HighLevelException e) {
             e.printStackTrace();
         }
     }
     static void a() throws HighLevelException {
         try {
             b();
         } catch(MidLevelException e) {
             throw new HighLevelException(e);
         }
     }
     static void b() throws MidLevelException {
         c();
     }
     static void c() throws MidLevelException {
         try {
             d();
         } catch(LowLevelException e) {
             throw new MidLevelException(e);
         }
     }
     static void d() throws LowLevelException {
        e();
     }
     static void e() throws LowLevelException {
         throw new LowLevelException();
     }
 }

 class HighLevelException extends Exception {
     HighLevelException(Throwable cause) { super(cause); }
 }

 class MidLevelException extends Exception {
     MidLevelException(Throwable cause)  { super(cause); }
 }

 class LowLevelException extends Exception {
 }
 
As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the try-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
 Exception in thread "main" java.lang.Exception: Something happened
  at Foo.bar(Foo.java:10)
  at Foo.main(Foo.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 0
          at Resource.close(Resource.java:26)
          at Foo.bar(Foo.java:9)
          ... 1 more
 
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

 Exception in thread "main" java.lang.Exception: Main block
  at Foo3.main(Foo3.java:7)
  Suppressed: Resource$CloseFailException: Resource ID = 2
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 1
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
 Caused by: java.lang.Exception: I did it
  at Foo3.main(Foo3.java:8)
 
Likewise, a suppressed exception can have a cause:
 Exception in thread "main" java.lang.Exception: Main block
  at Foo4.main(Foo4.java:6)
  Suppressed: Resource2$CloseFailException: Resource ID = 1
          at Resource2.close(Resource2.java:20)
          at Foo4.main(Foo4.java:5)
  Caused by: java.lang.Exception: Rats, you caught me
          at Resource2$CloseFailException.<init>(Resource2.java:45)
          ... 2 more
 

Official API Reference

All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException
Common superclass of exceptions thrown by reflective operations in core reflection.
Since:
1.7
See Also:
LinkageError, Serialized Form

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a class literal. For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form

Official API Reference

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired field.

If this Class object represents an array type, then this method does not find the length field of the array type.

Parameters:
name - the name of the field
Returns:
the Field object for the specified field in this class
Throws:
NoSuchFieldException - if a field with the specified name is not found.
NullPointerException - if name is null
SecurityException - If a security manager, s, is present and any of the following conditions is met:
  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared field
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
See Java Language Specification:
8.2 Class Members
8.3 Field Declarations
Since:
1.1

Official API Reference

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired field.

If this Class object represents an array type, then this method does not find the length field of the array type.

Parameters:
name - the name of the field
Returns:
the Field object for the specified field in this class
Throws:
NoSuchFieldException - if a field with the specified name is not found.
NullPointerException - if name is null
SecurityException - If a security manager, s, is present and any of the following conditions is met:
  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared field
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
See Java Language Specification:
8.2 Class Members
8.3 Field Declarations
Since:
1.1

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

Appends the specified element to the end of this list (optional operation).

Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.

Specified by:
add in interface Collection<E>
Parameters:
e - element to be appended to this list
Returns:
true (as specified by Collection.add(E))
Throws:
UnsupportedOperationException - if the add operation is not supported by this list
ClassCastException - if the class of the specified element prevents it from being added to this list
NullPointerException - if the specified element is null and this list does not permit null elements
IllegalArgumentException - if some property of this element prevents it from being added to this list

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Parameters:
x - The Object to be printed.

Official API Reference

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:
 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
 
This example was produced by running the program:
 class MyClass {
     public static void main(String[] args) {
         crunch(null);
     }
     static void crunch(int[] a) {
         mash(a);
     }
     static void mash(int[] b) {
         System.out.println(b[0]);
     }
 }
 
The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
 HighLevelException: MidLevelException: LowLevelException
         at Junk.a(Junk.java:13)
         at Junk.main(Junk.java:4)
 Caused by: MidLevelException: LowLevelException
         at Junk.c(Junk.java:23)
         at Junk.b(Junk.java:17)
         at Junk.a(Junk.java:11)
         ... 1 more
 Caused by: LowLevelException
         at Junk.e(Junk.java:30)
         at Junk.d(Junk.java:27)
         at Junk.c(Junk.java:21)
         ... 3 more
 
Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
 public class Junk {
     public static void main(String args[]) {
         try {
             a();
         } catch(HighLevelException e) {
             e.printStackTrace();
         }
     }
     static void a() throws HighLevelException {
         try {
             b();
         } catch(MidLevelException e) {
             throw new HighLevelException(e);
         }
     }
     static void b() throws MidLevelException {
         c();
     }
     static void c() throws MidLevelException {
         try {
             d();
         } catch(LowLevelException e) {
             throw new MidLevelException(e);
         }
     }
     static void d() throws LowLevelException {
        e();
     }
     static void e() throws LowLevelException {
         throw new LowLevelException();
     }
 }

 class HighLevelException extends Exception {
     HighLevelException(Throwable cause) { super(cause); }
 }

 class MidLevelException extends Exception {
     MidLevelException(Throwable cause)  { super(cause); }
 }

 class LowLevelException extends Exception {
 }
 
As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the try-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
 Exception in thread "main" java.lang.Exception: Something happened
  at Foo.bar(Foo.java:10)
  at Foo.main(Foo.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 0
          at Resource.close(Resource.java:26)
          at Foo.bar(Foo.java:9)
          ... 1 more
 
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

 Exception in thread "main" java.lang.Exception: Main block
  at Foo3.main(Foo3.java:7)
  Suppressed: Resource$CloseFailException: Resource ID = 2
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 1
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
 Caused by: java.lang.Exception: I did it
  at Foo3.main(Foo3.java:8)
 
Likewise, a suppressed exception can have a cause:
 Exception in thread "main" java.lang.Exception: Main block
  at Foo4.main(Foo4.java:6)
  Suppressed: Resource2$CloseFailException: Resource ID = 1
          at Resource2.close(Resource2.java:20)
          at Foo4.main(Foo4.java:5)
  Caused by: java.lang.Exception: Rats, you caught me
          at Resource2$CloseFailException.<init>(Resource2.java:45)
          ... 2 more
 

Official API Reference

All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException
Common superclass of exceptions thrown by reflective operations in core reflection.
Since:
1.7
See Also:
LinkageError, Serialized Form

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a class literal. For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:
 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
 
This example was produced by running the program:
 class MyClass {
     public static void main(String[] args) {
         crunch(null);
     }
     static void crunch(int[] a) {
         mash(a);
     }
     static void mash(int[] b) {
         System.out.println(b[0]);
     }
 }
 
The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
 HighLevelException: MidLevelException: LowLevelException
         at Junk.a(Junk.java:13)
         at Junk.main(Junk.java:4)
 Caused by: MidLevelException: LowLevelException
         at Junk.c(Junk.java:23)
         at Junk.b(Junk.java:17)
         at Junk.a(Junk.java:11)
         ... 1 more
 Caused by: LowLevelException
         at Junk.e(Junk.java:30)
         at Junk.d(Junk.java:27)
         at Junk.c(Junk.java:21)
         ... 3 more
 
Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
 public class Junk {
     public static void main(String args[]) {
         try {
             a();
         } catch(HighLevelException e) {
             e.printStackTrace();
         }
     }
     static void a() throws HighLevelException {
         try {
             b();
         } catch(MidLevelException e) {
             throw new HighLevelException(e);
         }
     }
     static void b() throws MidLevelException {
         c();
     }
     static void c() throws MidLevelException {
         try {
             d();
         } catch(LowLevelException e) {
             throw new MidLevelException(e);
         }
     }
     static void d() throws LowLevelException {
        e();
     }
     static void e() throws LowLevelException {
         throw new LowLevelException();
     }
 }

 class HighLevelException extends Exception {
     HighLevelException(Throwable cause) { super(cause); }
 }

 class MidLevelException extends Exception {
     MidLevelException(Throwable cause)  { super(cause); }
 }

 class LowLevelException extends Exception {
 }
 
As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the try-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
 Exception in thread "main" java.lang.Exception: Something happened
  at Foo.bar(Foo.java:10)
  at Foo.main(Foo.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 0
          at Resource.close(Resource.java:26)
          at Foo.bar(Foo.java:9)
          ... 1 more
 
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

 Exception in thread "main" java.lang.Exception: Main block
  at Foo3.main(Foo3.java:7)
  Suppressed: Resource$CloseFailException: Resource ID = 2
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 1
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
 Caused by: java.lang.Exception: I did it
  at Foo3.main(Foo3.java:8)
 
Likewise, a suppressed exception can have a cause:
 Exception in thread "main" java.lang.Exception: Main block
  at Foo4.main(Foo4.java:6)
  Suppressed: Resource2$CloseFailException: Resource ID = 1
          at Resource2.close(Resource2.java:20)
          at Foo4.main(Foo4.java:5)
  Caused by: java.lang.Exception: Rats, you caught me
          at Resource2$CloseFailException.<init>(Resource2.java:45)
          ... 2 more
 

Official API Reference

All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException
Common superclass of exceptions thrown by reflective operations in core reflection.
Since:
1.7
See Also:
LinkageError, Serialized Form

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a class literal. For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

Returns an unmodifiable list containing one element. See Unmodifiable Lists for details.
Type Parameters:
E - the List's element type
Parameters:
e1 - the single element
Returns:
a List containing the specified element
Throws:
NullPointerException - if the element is null
Since:
9

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Parameters:
x - The Object to be printed.

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Parameters:
c - the collection whose elements are to be placed into this list
Throws:
NullPointerException - if the specified collection is null

Official API Reference

Type Parameters:
E - the type of elements in this list
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Unmodifiable Lists

The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

This interface is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, ArrayList, LinkedList, Vector, Arrays.asList(Object[]), Collections.nCopies(int, Object), Collections.EMPTY_LIST, AbstractList, AbstractSequentialList

Official API Reference

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.

The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.

The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort does not have to be a mergesort, but it does have to be stable.)

The "destructive" algorithms contained in this class, that is, the algorithms that modify the collection on which they operate, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s), such as the set method. These algorithms may, but are not required to, throw this exception if an invocation would have no effect on the collection. For example, invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException.

This class is a member of the Java Collections Framework.

Since:
1.2
See Also:
Collection, Set, List, Map

Official API Reference

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The specified list must be modifiable, but need not be resizable.

Implementation Note:
This implementation defers to the List.sort(Comparator) method using the specified list and a null comparator.
Type Parameters:
T - the class of the objects in the list
Parameters:
list - the list to be sorted.
Throws:
ClassCastException - if the list contains elements that are not mutually comparable (for example, strings and integers).
UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
IllegalArgumentException - (optional) if the implementation detects that the natural ordering of the list elements is found to violate the Comparable contract
See Also:
List.sort(Comparator)

Official API Reference

Returns the element at the specified position in this list.
Parameters:
index - index of the element to return
Returns:
the element at the specified position in this list
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Official API Reference

Returns the element at the specified position in this list.
Parameters:
index - index of the element to return
Returns:
the element at the specified position in this list
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Official API Reference

Returns the element at the specified position in this list.
Parameters:
index - index of the element to return
Returns:
the element at the specified position in this list
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
Specified by:
size in interface Collection<E>
Returns:
the number of elements in this list

Official API Reference

Returns the element at the specified position in this list.
Parameters:
index - index of the element to return
Returns:
the element at the specified position in this list
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

Official API Reference

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
Specified by:
size in interface Collection<E>
Returns:
the number of elements in this list

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
Specified by:
size in interface Collection<E>
Returns:
the number of elements in this list

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Indicates that a method declaration is intended to override a method declaration in a supertype. If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:
See Java Language Specification:
8.4.8 Inheritance, Overriding, and Hiding
9.4.1 Inheritance and Overriding
9.6.4.4 @Override
Since:
1.5

This class is declared at the end of this file.

The unique name of the class, including the package name.

For example:

Literal expressions directly defines constant values in Java. For example, an int literal can be 123 and a String literal can be "hello".

A class literal defines a value of type Class. It takes the form of the class name followed by .class. For example, String.class or Book.class.

getClass() will return the exact run-time class of the object on which it is called, rather than a parent class (or interface). For example, in the following code

List<String> x = new ArrayList<>();
Class<?> actualClass = x.getClass();

the variable actualClass represents the class ArrayList, even though the variable x has the type List (which is a supertype of ArrayList).

The method Class.forName(String) throws a ClassNotFoundException if there is no class with the given fully qualified name. This can happen if there is a typo in the name, the simple name is used (without the package), dots (.) are used instead of dollar signs ($) to indicate nested classes, etc.

The unique name of the class, including the package name.

For example:

fields declared in parent classes

methods declared in parent classes

to get those, call getDeclaredConstructors()

Contrary to fields and methods, constructors are not inherited from parent classes (according to the Reflection API).

Many methods from the Reflection API throw different exceptions, most of them are actually subtypes of ReflectiveOperationException, which allows to catch all potential exceptions in the same block.

To get access to fields of an object X, the first thing to do is get a reference to a Class object that represents the class of X. Here, we get a reference to the class Book using a class literal (Book.class).

This is a class literal: an expression that encodes a constant value of type Class, similar to how the string literal "hello" encodes a constant value of type String.

Here, the class literal represents the class Book.

When calling set, the first argument must be the object for which we need to change the field value. Here, it's the book variable. This argument is required because up to this point, the book variable isn't involved, meaning that the previous code would be the same to change the title of any book object.

If the field to change is a static field, the first argument isn't used, so we can use null (e.g., staticField.set(null, newValue)).

The second argument is the new value.

The argument of get is the object of which we want to field value. Here, we want the authors of the book object.

If the field is static (i.e., not associated with any object), the argument isn't used, so we can pass the value null.

Many methods from the Reflection API throw different exceptions, most of them are actually subtypes of ReflectiveOperationException, which allows to catch all potential exceptions in the same block.

To get access to methods of an object X, the first thing to do is get a reference to a Class object that represents the class of X. Here, we get a reference to the class Book using a class literal (Book.class).

This is a class literal: an expression that encodes a constant value of type Class, similar to how the string literal "hello" encodes a constant value of type String.

Here, the class literal represents the class Book.

The first argument of getDeclaredMethod is the name of the method, and the following arguments are the types of its parameters, represented by Class objects. Here, formatAuthors has only one parameter, of type boolean, so we use the class literal boolean.class.

Although boolean is a primitive type in Java, and therefore not a class, we can still use a class literal in a similar way, and get a Class object that represents this primitive type.

If a method is static, there is no implicit argument, so the first argument of invoke is ignored. We can use the value null.

Many methods from the Reflection API throw different exceptions, most of them are actually subtypes of ReflectiveOperationException, which allows to catch all potential exceptions in the same block.

To get access to constructors of a class, the first thing to do is get a reference to a Class object that represents that class. Here, we get a reference to the class Book using a class literal (Book.class).

This is a class literal: an expression that encodes a constant value of type Class, similar to how the string literal "hello" encodes a constant value of type String.

Here, the class literal represents the class Book.


💡newInstance

newInstance creates a new object of the target class (here, Book), using the constructor represented the Constructor object. The arguments to newInstance are the same arguments we would usually give to the constructor (i.e., the title and authors).

public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

Official API Reference

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

If the number of formal parameters required by the underlying constructor is 0, the supplied initargs array may be of length 0 or null.

If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; see section 15.9.3 of The Java Language Specification.

If the required access and argument checks succeed and the instantiation will proceed, the constructor's declaring class is initialized if it has not already been initialized.

If the constructor completes normally, returns the newly created and initialized instance.

Parameters:
initargs - array of objects to be passed as arguments to the constructor call; values of primitive types are wrapped in a wrapper object of the appropriate type (e.g. a float in a Float)
Returns:
a new object created by calling the constructor this object represents
Throws:
IllegalAccessException - if this Constructor object is enforcing Java language access control and the underlying constructor is inaccessible.
IllegalArgumentException - if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if this constructor pertains to an enum type.
InstantiationException - if the class that declares the underlying constructor represents an abstract class.
InvocationTargetException - if the underlying constructor throws an exception.
ExceptionInInitializerError - if the initialization provoked by this method fails.



💡getDeclaredConstructor

The arguments of getDeclaredConstructor are the types of its parameters, represented by Class objects. Here, the constructor has two parameters, of type String and List, and we use class literals to represent these types.

public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

Official API Reference

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
Parameters:
parameterTypes - the parameter array
Returns:
The Constructor object for the constructor with the specified parameter list
Throws:
NoSuchMethodException - if a matching method is not found.
SecurityException - If a security manager, s, is present and any of the following conditions is met:
  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared constructor
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
Since:
1.1



💡Constructor<Book>

To reflectively create objects of a class, we get a reference to an object of class Constructor. We can get this reference using the method getDeclaredConstructor() on the Class object.

public final class Constructor<T> extends Executable

Official API Reference

Type Parameters:
T - the class in which the constructor is declared
All Implemented Interfaces:
AnnotatedElement, GenericDeclaration, Member
Constructor provides information about, and access to, a single constructor for a class.

Constructor permits widening conversions to occur when matching the actual parameters to newInstance() with the underlying constructor's formal parameters, but throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getConstructors(), Class.getConstructor(Class[]), Class.getDeclaredConstructors()



💡invoke(book, true)

To invoke a method represented by a Method object, we call invoke. The first argument is the implicit argument of the invoked method, i.e., the book object on which we would normally call this method. The following arguments are all the explicit arguments. Here, there is only one explicit argument, which is a boolean.

invoke returns the value that the invoked method would normally return.

public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException

Official API Reference

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

If the underlying method is static, then the specified obj argument is ignored. It may be null.

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null.

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, section 15.12.4.4; in particular, overriding based on the runtime type of the target object may occur.

If the underlying method is static, the class that declared the method is initialized if it has not already been initialized.

If the method completes normally, the value it returns is returned to the caller of invoke; if the value has a primitive type, it is first appropriately wrapped in an object. However, if the value has the type of an array of a primitive type, the elements of the array are not wrapped in objects; in other words, an array of primitive type is returned. If the underlying method return type is void, the invocation returns null.

Parameters:
obj - the object the underlying method is invoked from
args - the arguments used for the method call
Returns:
the result of dispatching the method represented by this object on obj with parameters args
Throws:
IllegalAccessException - if this Method object is enforcing Java language access control and the underlying method is inaccessible.
IllegalArgumentException - if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.
InvocationTargetException - if the underlying method throws an exception.
NullPointerException - if the specified object is null and the method is an instance method.
ExceptionInInitializerError - if the initialization provoked by this method fails.



💡setAccessible

Because the method we want to invoke is private (i.e., not normally accessible here), it's necessary to call setAccessible(true) before invoking the method.

public void setAccessible(boolean flag)

Official API Reference

Description copied from class: AccessibleObject
Set the accessible flag for this reflected object to the indicated boolean value. A value of true indicates that the reflected object should suppress checks for Java language access control when it is used. A value of false indicates that the reflected object should enforce checks for Java language access control when it is used, with the variation noted in the class description.

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

This method cannot be used to enable access to private members, members with default (package) access, protected instance members, or protected constructors when the declaring class is in a different module to the caller and the package containing the declaring class is not open to the caller's module.

This method cannot be used to enable write access to a non-modifiable final field. The following fields are non-modifiable:

The accessible flag when true suppresses Java language access control checks to only enable read access to these non-modifiable final fields.

If there is a security manager, its checkPermission method is first called with a ReflectPermission("suppressAccessChecks") permission.

Overrides:
setAccessible in class AccessibleObject
Parameters:
flag - the new value for the accessible flag
Throws:
InaccessibleObjectException - if access cannot be enabled
SecurityException - if the request is denied by the security manager
See Also:
AccessibleObject.trySetAccessible(), MethodHandles.privateLookupIn(java.lang.Class<?>, java.lang.invoke.MethodHandles.Lookup)



💡Method

To invoke methods of an object (or static methods of a class), we get a reference to an object of class Method. We can get this reference using the method getDeclaredMethod() on the Class object.

public final class Method extends Executable

Official API Reference

All Implemented Interfaces:
AnnotatedElement, GenericDeclaration, Member
A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).

A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getMethods(), Class.getMethod(String, Class[]), Class.getDeclaredMethods(), Class.getDeclaredMethod(String, Class[])



💡get

The method get returns a reference to the value of the field. If the field is a mutable object, as is the case here (a List), we can modify it, and the modifications will be reflected in the original book object.

public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException

Official API Reference

Returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.

The underlying field's value is obtained as follows:

If the underlying field is a static field, the obj argument is ignored; it may be null.

Otherwise, the underlying field is an instance field. If the specified obj argument is null, the method throws a NullPointerException. If the specified object is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException.

If this Field object is enforcing Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException. If the underlying field is static, the class that declared the field is initialized if it has not already been initialized.

Otherwise, the value is retrieved from the underlying instance or static field. If the field has a primitive type, the value is wrapped in an object before being returned, otherwise it is returned as is.

If the field is hidden in the type of obj, the field's value is obtained according to the preceding rules.

Parameters:
obj - object from which the represented field's value is to be extracted
Returns:
the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned
Throws:
IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).
NullPointerException - if the specified object is null and the field is an instance field.
ExceptionInInitializerError - if the initialization provoked by this method fails.



💡setAccessible

The field authors of class Book is private, meaning that it can't be accessed or modified outside the class Book (i.e., here). To make it possible to get the authors, we need to call setAccessible(true) on the field object.

public void setAccessible(boolean flag)

Official API Reference

Description copied from class: AccessibleObject
Set the accessible flag for this reflected object to the indicated boolean value. A value of true indicates that the reflected object should suppress checks for Java language access control when it is used. A value of false indicates that the reflected object should enforce checks for Java language access control when it is used, with the variation noted in the class description.

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

This method cannot be used to enable access to private members, members with default (package) access, protected instance members, or protected constructors when the declaring class is in a different module to the caller and the package containing the declaring class is not open to the caller's module.

This method cannot be used to enable write access to a non-modifiable final field. The following fields are non-modifiable:

The accessible flag when true suppresses Java language access control checks to only enable read access to these non-modifiable final fields.

If there is a security manager, its checkPermission method is first called with a ReflectPermission("suppressAccessChecks") permission.

Overrides:
setAccessible in class AccessibleObject
Parameters:
flag - the new value for the accessible flag
Throws:
InaccessibleObjectException - if access cannot be enabled
SecurityException - if the request is denied by the security manager
See Also:
AccessibleObject.trySetAccessible(), MethodHandles.privateLookupIn(java.lang.Class<?>, java.lang.invoke.MethodHandles.Lookup)



💡Field authorField

To manipulate fields of an object (or static fields of a class), we get a reference to an object of class Field. We can get this reference using the method getDeclaredField() on the Class object.

Note that the object that we want to modify (i.e., the actual book object) isn't needed.

public final class Field extends AccessibleObject implements Member

Official API Reference

All Implemented Interfaces:
AnnotatedElement, Member
A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.

A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getFields(), Class.getField(String), Class.getDeclaredFields(), Class.getDeclaredField(String)



💡set

The method set is used to change the value of a field.

public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException

Official API Reference

Sets the field represented by this Field object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.

The operation proceeds as follows:

If the underlying field is static, the obj argument is ignored; it may be null.

Otherwise the underlying field is an instance field. If the specified object argument is null, the method throws a NullPointerException. If the specified object argument is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException.

If this Field object is enforcing Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException.

If the underlying field is final, this Field object has write access if and only if the following conditions are met:

If any of the above checks is not met, this method throws an IllegalAccessException.

Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field.

If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type. If this attempt fails, the method throws an IllegalArgumentException.

If, after possible unwrapping, the new value cannot be converted to the type of the underlying field by an identity or widening conversion, the method throws an IllegalArgumentException.

If the underlying field is static, the class that declared the field is initialized if it has not already been initialized.

The field is set to the possibly unwrapped and widened new value.

If the field is hidden in the type of obj, the field's value is set according to the preceding rules.

Parameters:
obj - the object whose field should be modified
value - the new value for the field of obj being modified
Throws:
IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible or final; or if this Field object has no write access.
IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails.
NullPointerException - if the specified object is null and the field is an instance field.
ExceptionInInitializerError - if the initialization provoked by this method fails.



💡setAccessible

The field title of class Book is private, meaning that it can't be accessed or modified outside the class Book (i.e., here). To make it possible to change the title, we need to call setAccessible(true) on the field object.

public void setAccessible(boolean flag)

Official API Reference

Description copied from class: AccessibleObject
Set the accessible flag for this reflected object to the indicated boolean value. A value of true indicates that the reflected object should suppress checks for Java language access control when it is used. A value of false indicates that the reflected object should enforce checks for Java language access control when it is used, with the variation noted in the class description.

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

This method cannot be used to enable access to private members, members with default (package) access, protected instance members, or protected constructors when the declaring class is in a different module to the caller and the package containing the declaring class is not open to the caller's module.

This method cannot be used to enable write access to a non-modifiable final field. The following fields are non-modifiable:

The accessible flag when true suppresses Java language access control checks to only enable read access to these non-modifiable final fields.

If there is a security manager, its checkPermission method is first called with a ReflectPermission("suppressAccessChecks") permission.

Overrides:
setAccessible in class AccessibleObject
Parameters:
flag - the new value for the accessible flag
Throws:
InaccessibleObjectException - if access cannot be enabled
SecurityException - if the request is denied by the security manager
See Also:
AccessibleObject.trySetAccessible(), MethodHandles.privateLookupIn(java.lang.Class<?>, java.lang.invoke.MethodHandles.Lookup)



💡Field titleField

To manipulate fields of an object (or static fields of a class), we get a reference to an object of class Field. We can get this reference using the method getDeclaredField() on the Class object.

Note that the object that we want to modify (i.e., the actual book object) isn't needed.

public final class Field extends AccessibleObject implements Member

Official API Reference

All Implemented Interfaces:
AnnotatedElement, Member
A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.

A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

Since:
1.1
See Also:
Member, Class, Class.getFields(), Class.getField(String), Class.getDeclaredFields(), Class.getDeclaredField(String)



💡toGenericString()

This method returns information about the field in a String, most likely to be showed as is to humans.

To get specific information, there are methods like getName(), getModifiers(), and getType().

public String toGenericString()

Official API Reference

Returns a string describing this Constructor, including type parameters. The string is formatted as the constructor access modifiers, if any, followed by an angle-bracketed comma separated list of the constructor's type parameters, if any, including informative bounds of the type parameters, if any, followed by the fully-qualified name of the declaring class, followed by a parenthesized, comma-separated list of the constructor's generic formal parameter types. If this constructor was declared to take a variable number of arguments, instead of denoting the last parameter as "Type[]", it is denoted as "Type...". A space is used to separate access modifiers from one another and from the type parameters or class name. If there are no type parameters, the type parameter list is elided; if the type parameter list is present, a space separates the list from the class name. If the constructor is declared to throw exceptions, the parameter list is followed by a space, followed by the word "throws" followed by a comma-separated list of the generic thrown exception types.

The only possible modifiers for constructors are the access modifiers public, protected or private. Only one of these may appear, or none if the constructor has default (package) access.

Specified by:
toGenericString in class Executable
Returns:
a string describing this Constructor, include type parameters
See Java Language Specification:
8.8.3 Constructor Modifiers
8.9.2 Enum Body Declarations
Since:
1.5



💡getDeclaredConstructors()

This method returns all constructors (public or not) for this class.

public Constructor<?>[] getDeclaredConstructors() throws SecurityException

Official API Reference

Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors. The elements in the array returned are not sorted and are not in any particular order. If the class has a default constructor, it is included in the returned array. This method returns an array of length 0 if this Class object represents an interface, a primitive type, an array class, or void.

See The Java Language Specification, section 8.2.

Returns:
the array of Constructor objects representing all the declared constructors of this class
Throws:
SecurityException - If a security manager, s, is present and any of the following conditions is met:
  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared constructors within this class
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
Since:
1.1



💡toGenericString()

This method returns information about the method in a String, most likely to be showed as is to humans.

To get specific information, there are methods like getName(), getModifiers(), and getType().

public String toGenericString()

Official API Reference

Returns a string describing this Method, including type parameters. The string is formatted as the method access modifiers, if any, followed by an angle-bracketed comma-separated list of the method's type parameters, if any, including informative bounds of the type parameters, if any, followed by the method's generic return type, followed by a space, followed by the class declaring the method, followed by a period, followed by the method name, followed by a parenthesized, comma-separated list of the method's generic formal parameter types. If this method was declared to take a variable number of arguments, instead of denoting the last parameter as "Type[]", it is denoted as "Type...". A space is used to separate access modifiers from one another and from the type parameters or return type. If there are no type parameters, the type parameter list is elided; if the type parameter list is present, a space separates the list from the class name. If the method is declared to throw exceptions, the parameter list is followed by a space, followed by the word "throws" followed by a comma-separated list of the generic thrown exception types.

The access modifiers are placed in canonical order as specified by "The Java Language Specification". This is public, protected or private first, and then other modifiers in the following order: abstract, default, static, final, synchronized, native, strictfp.

Specified by:
toGenericString in class Executable
Returns:
a string describing this Method, include type parameters
See Java Language Specification:
8.4.3 Method Modifiers
9.4 Method Declarations
9.6.1 Annotation Type Elements
Since:
1.5



💡getDeclaredMethods()

This method returns all methods declared in this class. It doesn't include inherited methods, but it includes non public ones.

For this API, a constructor is not a method, and therefore getDeclaredMethods() will not return constructors.

To also get methods from parent classes, use getMethods() instead. However, this method only returns public methods.

public Method[] getDeclaredMethods() throws SecurityException

Official API Reference

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding .

If this Class object represents a type that has multiple declared methods with the same name and parameter types, but different return types, then the returned array has a Method object for each such method.

If this Class object represents a type that has a class initialization method <clinit>, then the returned array does not have a corresponding Method object.

If this Class object represents a class or interface with no declared methods, then the returned array has length 0.

If this Class object represents an array type, a primitive type, or void, then the returned array has length 0.

The elements in the returned array are not sorted and are not in any particular order.

Returns:
the array of Method objects representing all the declared methods of this class
Throws:
SecurityException - If a security manager, s, is present and any of the following conditions is met:
  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared methods within this class
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
See Java Language Specification:
8.2 Class Members
8.4 Method Declarations
Since:
1.1



💡toGenericString()

This method returns information about the field in a String, most likely to be showed as is to humans.

To get specific information, there are methods like getName(), getModifiers(), and getType().

public String toGenericString()

Official API Reference

Returns a string describing this Field, including its generic type. The format is the access modifiers for the field, if any, followed by the generic field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field.

The modifiers are placed in canonical order as specified by "The Java Language Specification". This is public, protected or private first, and then other modifiers in the following order: static, final, transient, volatile.

Returns:
a string describing this Field, including its generic type
See Java Language Specification:
8.3.1 Field Modifiers
Since:
1.5



💡getDeclaredFields()

This method returns all fields declared in this class. It doesn't include inherited fields, but it includes non public ones.

To also get fields from parent classes, use getFields() instead. However, this method only returns public fields.

public Field[] getDeclaredFields() throws SecurityException

Official API Reference

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes .

If this Class object represents a class or interface with no declared fields, then this method returns an array of length 0.

If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.

The elements in the returned array are not sorted and are not in any particular order.

Returns:
the array of Field objects representing all the declared fields of this class
Throws:
SecurityException - If a security manager, s, is present and any of the following conditions is met:
  • the caller's class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission("accessDeclaredMembers") denies access to the declared fields within this class
  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
See Java Language Specification:
8.2 Class Members
8.3 Field Declarations
Since:
1.1



💡getClass

getClass() will return the exact run-time class of the object on which it is called, rather than a parent class (or interface). For example, in the following code

List<String> x = new ArrayList<>();
Class<?> actualClass = x.getClass();

the variable actualClass represents the class ArrayList, even though the variable x has the type List (which is a supertype of ArrayList).

public final Class<?> getClass()

Official API Reference

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0;
Class<? extends Number> c = n.getClass();

Returns:
The Class object that represents the runtime class of this object.
See Java Language Specification:
15.8.2 Class Literals



💡Class<?>

To get information about a Java class (or interface), the first step is to get a reference to a Class object representing that class (or interface).

There are 3 ways to get a reference to a Class object:

  1. by parsing a String that contains the fully qualified name of the class with Class.forName(String),
  2. by using a class literal,
  3. by calling getClass() on an instance of that class.
public final class Class<T> extends Object implements Serializable, GenericDeclaration, Type, AnnotatedElement, TypeDescriptor.OfField<Class<?>>, Constable

Official API Reference

Type Parameters:
T - the type of the class modeled by this Class object. For example, the type of String.class is Class<String>. Use Class<?> if the class being modeled is unknown.
All Implemented Interfaces:
Serializable, Constable, TypeDescriptor, TypeDescriptor.OfField<Class<?>>, AnnotatedElement, GenericDeclaration, Type
Instances of the class Class represent classes and interfaces in a running Java application. An enum type and a record type are kinds of class; an annotation type is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class is derived from the bytes of a class file through the invocation of one of the following methods:

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass. A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule().

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }
 
It is also possible to get the Class object for a named type (or for void) using a . For example: System.out.println("The name of class Foo is: "+Foo.class.getName());

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

A class or interface created by the invocation of Lookup::defineHiddenClass is a hidden class or interface. All kinds of class, including enum types and record types, may be hidden classes; all kinds of interface, including annotation types, may be hidden interfaces. The name of a hidden class or interface is not a binary name, which means the following:

A hidden class or interface is never an array class, but may be the element type of an array. In all other respects, the fact that a class or interface is hidden has no bearing on the characteristics exposed by the methods of class Class.

See Java Language Specification:
15.8.2 Class Literals
Since:
1.0
See Also:
ClassLoader.defineClass(byte[], int, int), Serialized Form