Reflection in Java (2001)

When programming Java, you are constantly referring to classes and objects directly. For example calling a constructor like this:

    ChryslerCar myChrysler = new ChryslerCar("Stratus");

In this example this can work because you can at compile-time have the necessary "ChryslerCar" class in your classpath.

However, suppose you wanted to invoke a method on some object, but you cannot make this work at compile-time. In the example this is the case when the "ChryslerCar" class is not available at compile-time.

You would have a problem if JavaSoft did not introduce Java Reflection in Java 1.1. Luckily they did!

Java reflection is a standardized Java API that you can find in the "java.lang.reflect" package. It makes it possible to do introspection of classes and objects. You can query a Java class about its properties, methods, constructors, etc... The reflection feature also allows you to operate on each of them.

Java reflection is the lowest-level Java VM access that is possible. It is especially being used for low-coupling, less dependencies between classes, error handling, property-based class invocation, etc..

The reflection feature may not seem much when you see it at first, but it's impossible to do in other languages such as C, C++, or Fortran. The names and properties of functions in these other languages are gone by the time the program is executed. In technical terms, these other languages have "early binding", whereas the Java has "late binding".

The example with reflection:

	// locate the class we need
	Class chryslerClass = Class.forName("ChryslerCar");

	// find the constructor
	Class[] paramTypes = { String.class };
	java.lang.reflect.Constructor con = chryslerClass.getConstructor(paramTypes);

	// instantiate, so we get an object
	Object[] params = { "Stratus" };
	Object chryslerInstance = con.newInstance(params);

Java reflection does have a downside though: degraded performance. The reflection functionality requires the Java VM to do additional analysing of classes and objects that would normally not be necessary during run-time: this would already have been performed during compile-time by the Java compiler.

Conclusion:
Using reflection requires has the advantage of more flexibility at the cost of the overhead of more time needed to execute code.

Related links:
API documentation *
Reflection Frequently Asked Questions *
Online Reflection Tutorial *
Java Core Reflection Specification *