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", );
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);
}
}
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
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.
add
in interface Collection<E>
e
- element to be appended to this list
true
(as specified by Collection.add(E)
)
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
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
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.
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.
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.
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.
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.
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.
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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. 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.
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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. Class
.
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 moreNote 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 moreNote 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
forName
method in class Class
. findSystemClass
method in class ClassLoader
. loadClass
method in class ClassLoader
. 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."
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.
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.
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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. Class
.
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.
className
- the fully qualified name of the desired class.
Class
object for the class with the specified name.
LinkageError
- if the linkage fails
ExceptionInInitializerError
- if the initialization provoked by this method fails
ClassNotFoundException
- if the class cannot be located
Class
object.
If this Class
object represents a class or interface, not an array class, then:
N + '/' + <suffix>
where N
is the binary name indicated by the class
file passed to Lookup::defineHiddenClass
, and <suffix>
is an unqualified name. 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 Type | Encoding |
---|---|
boolean |
Z |
byte |
B |
char |
C |
class or interface with binary name N | L N; |
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"
Class
object.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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.
print(String)
and then println()
.
x
- The String
to be printed.
T
- the class in which the constructor is declared
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.
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.
line.separator
, and is not necessarily a single newline character ('\n'
).
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.
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 moreNote 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 moreNote 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
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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. Class
.
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.
name
- the name of the field
Field
object for the specified field in this class
NoSuchFieldException
- if a field with the specified name is not found.
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared field s.checkPackageAccess()
denies access to the package of this class 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.
name
- the name of the field
Field
object for the specified field in this class
NoSuchFieldException
- if a field with the specified name is not found.
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared field s.checkPackageAccess()
denies access to the package of this class E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
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.
add
in interface Collection<E>
e
- element to be appended to this list
true
(as specified by Collection.add(E)
)
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
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.
print(String)
and then println()
.
x
- The Object
to be printed.
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 moreNote 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 moreNote 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
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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. Class
.
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.
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.
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.
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.
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.
print(String)
and then println()
.
x
- The String
to be printed.
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 moreNote 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 moreNote 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
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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. Class
.
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.
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.
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
E
- the List
's element type
e1
- the single element
List
containing the specified element
NullPointerException
- if the element is null
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.
print(String)
and then println()
.
x
- The Object
to be printed.
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.
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.
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
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.
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.
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
c
- the collection whose elements are to be placed into this list
NullPointerException
- if the specified collection is null
E
- the type of elements in this list
Collection<E>
, Iterable<E>
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.
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:
UnsupportedOperationException
to be thrown. However, if the contained elements are themselves mutable, this may cause the List's contents to appear to change. null
elements. Attempts to create them with null
elements result in NullPointerException
. subList
views implement the RandomAccess
interface. ==
), identity hash code, and synchronization) are unreliable and should be avoided. This interface is a member of the Java Collections Framework.
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.
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.
List.sort(Comparator)
method using the specified list and a null
comparator.
T
- the class of the objects in the list
list
- the list to be sorted.
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
index
- index of the element to return
IndexOutOfBoundsException
- if the index is out of range (index < 0 || index >= size()
)
index
- index of the element to return
IndexOutOfBoundsException
- if the index is out of range (index < 0 || index >= size()
)
index
- index of the element to return
IndexOutOfBoundsException
- if the index is out of range (index < 0 || index >= size()
)
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.
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.
Integer.MAX_VALUE
elements, returns Integer.MAX_VALUE
.
size
in interface Collection<E>
index
- index of the element to return
IndexOutOfBoundsException
- if the index is out of range (index < 0 || index >= size()
)
Integer.MAX_VALUE
elements, returns Integer.MAX_VALUE
.
size
in interface Collection<E>
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.
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.
Integer.MAX_VALUE
elements, returns Integer.MAX_VALUE
.
size
in interface Collection<E>
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.
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.
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.
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.
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.
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.
This class is declared at the end of this file.
The unique name of the class, including the package name.
For example:
icse.demo.reflection.Book
java.lang.String
java.util.Map
java.util.Map$Entry
(Entry
is a nested class that is a member of the Map
class)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:
icse.demo.reflection.Book
java.lang.String
java.util.Map
java.util.Map$Entry
(Entry
is a nested class that is a member of the Map
class)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
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).
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.
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
)
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.
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.
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.
parameterTypes
- the parameter array
Constructor
object for the constructor with the specified parameter list
NoSuchMethodException
- if a matching method is not found.
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared constructor s.checkPackageAccess()
denies access to the package of this class 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.
T
- the class in which the constructor is declared
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.
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.
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.
obj
- the object the underlying method is invoked from
args
- the arguments used for the method call
obj
with parameters args
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.
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.
AccessibleObject
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:
C
and D
are in the same module. public
and D
is public
in a package that the module containing D
exports
to at least the module containing C
. protected
static
, D
is public
in a package that the module containing D
exports to at least the module containing C
, and C
is a subclass of D
. D
is in a package that the module containing D
opens
to at least the module containing C
. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D
is in an unnamed or open module. 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.
setAccessible
in class AccessibleObject
flag
- the new value for the accessible
flag
InaccessibleObjectException
- if access cannot be enabled
SecurityException
- if the request is denied by the security manager
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.
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.
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.
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.
obj
- object from which the represented field's value is to be extracted
obj
; primitive values are wrapped in an appropriate object before being returned
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.
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.
AccessibleObject
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:
C
and D
are in the same module. public
and D
is public
in a package that the module containing D
exports
to at least the module containing C
. protected
static
, D
is public
in a package that the module containing D
exports to at least the module containing C
, and C
is a subclass of D
. D
is in a package that the module containing D
opens
to at least the module containing C
. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D
is in an unnamed or open module. 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.
setAccessible
in class AccessibleObject
flag
- the new value for the accessible
flag
InaccessibleObjectException
- if access cannot be enabled
SecurityException
- if the request is denied by the security manager
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.
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.
The method set
is used to change the value of a field.
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:
setAccessible(true)
has succeeded for this Field
object;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.
obj
- the object whose field should be modified
value
- the new value for the field of obj
being modified
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.
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.
AccessibleObject
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:
C
and D
are in the same module. public
and D
is public
in a package that the module containing D
exports
to at least the module containing C
. protected
static
, D
is public
in a package that the module containing D
exports to at least the module containing C
, and C
is a subclass of D
. D
is in a package that the module containing D
opens
to at least the module containing C
. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D
is in an unnamed or open module. 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.
setAccessible
in class AccessibleObject
flag
- the new value for the accessible
flag
InaccessibleObjectException
- if access cannot be enabled
SecurityException
- if the request is denied by the security manager
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.
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.
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()
.
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.
toGenericString
in class Executable
Constructor
, include type parameters
This method returns all constructors (public or not) for this class.
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.
Constructor
objects representing all the declared constructors of this class
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared constructors within this class s.checkPackageAccess()
denies access to the package of this class 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()
.
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
.
toGenericString
in class Executable
Method
, include type parameters
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.
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.
Method
objects representing all the declared methods of this class
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared methods within this class s.checkPackageAccess()
denies access to the package of this class 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()
.
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
.
Field
, including its generic type
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.
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.
Field
objects representing all the declared fields of this class
SecurityException
- If a security manager, s, is present and any of the following conditions is met:
s.checkPermission
method with RuntimePermission("accessDeclaredMembers")
denies access to the declared fields within this class s.checkPackageAccess()
denies access to the package of this 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
).
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();
Class
object that represents the runtime class of this object.
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:
String
that contains the fully qualified name of the class with Class.forName(String)
,getClass()
on an instance of that class.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.
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:
ClassLoader::defineClass
java.lang.invoke.MethodHandles.Lookup::defineClass
java.lang.invoke.MethodHandles.Lookup::defineHiddenClass
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:
Class::describeConstable
, ClassDesc::of
, or ClassDesc::ofDescriptor
. Class::forName
or ClassLoader::loadClass
. Class
.