Reflection Overview
Reflection is the mechanism by which Java exposes the features of a class during runtime, allowing Java programs to enumerate and access a class's methods, fields, and constructors as objects. The programmer can use these objects to access an object's features using runtime API constructs instead of compile-time language constructs.
The central class for reflection in Java is the java.lang.Class. Instances of the class Class represent classes and interfaces in a running Java application. 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.
Representing Java object with classes
Alongside afore-mentioned Class class, numerous Java classes representing program constructs exist, e.g.:
To gather package information, java.lang.Package class could be used.
Reflection for programmatical Java objects manipulation
Reflection is the powerful mechanism Java
provides to inspect structures,
but it also provides the way to programmatically create and manipulate Java objects, e.g.:
// Creating ArrayList instance by reflection
ArrayList arrayList = ArrayList.class.newInstance(); // Calling 'add' method ArrayList.class.getMethod("add", Object.class).invoke(arrayList, "Hello"); ArrayList.class.getMethod("add", Object.class).invoke(arrayList, "World!"); // Printing the result System.out.println(arrayList); // Will print [Hello, World!]
Reflection and performance
Reflection may be seen as equivalent to regular Java object creation and manipulation, but it's worth noting that reflection is much less effective, so it should be used with care and only in cases when regular language constructs usage can't be used to solve the problem. Code that uses reflection is also harder to read and maintain.