Languages‎ > ‎Java‎ > ‎

Reflective programming

Java

The following is an example in Java using the Java package java.lang.reflect. Consider two pieces of code

// Without reflection
Foo foo = new Foo();
foo.hello();

// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);

Both code fragments create an instance of a class Foo and call its hello() method. The difference is that, in the first fragment, the names of the class and method are hard-coded; it is not possible to use a class of another name. In the second fragment, the names of the class and method can easily be made to vary at runtime. The downside is that the second version is harder to read, and is not protected by compile-time syntax and semantic checking. For example, if no class Foo exists, an error will be generated at compile time for the first version. The equivalent error will only be generated at run time for the second version.

Comments