Java Reflection Tutorial

Language/JAVA 2014. 12. 1. 11:37

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

Java Reflection is quite powerful and can be very useful. For instance, when mapping objects to tables in a database at runtime, like Butterfly Persistence does. Or, when mapping the statements in a script language to method calls on real objects at runtime, like Butterfly Container does when parsing its configuration scripts.

There are already numerous Java Reflection Tutorials on the internet. However, most of them, including Sun's own Java Reflection tutorial, only scratch the surface of Java Reflection and its possibilities.

This tutorial will get into Java reflection in more depth than most of the tutorials I have seen. It will explain the basics of Java Reflection including how to work with arrays, annotations, generics and dynamic proxies, and do dynamic class loading and reloading. It will also show you how to do more specific tasks, like reading all getter methods of a class, or accessing private fields and methods of a class. This tutorial will also clear up some of the confusion out there about what Generics information is available at runtime. Some people claim that all Generics information is lost at runtime. This is not true.

This tutorial describes the version of Java Reflection found in Java 6.

Java Reflection Example

Here is a quick Java Reflection example to show you what using reflection looks like:

Method[] methods = MyObject.class.getMethods();

for(Method method : methods){
    System.out.println("method = " + method.getName());
}

This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.

Exactly how all this works is explained in further detail throughout the rest of this tutorial (in other texts).

Table of Contents

You can find a list of all the topics covered in this tutorial at the top left of the page. This list is repeated on all pages in this tutorial.


출처 - http://tutorials.jenkov.com/java-reflection/index.html

: