Hello World

Java Reflection Tutorial 본문

Java/Core

Java Reflection Tutorial

EnterKey 2016. 1. 11. 16:12
반응형

This tutorial is about reflection, the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of the program at runtime.

We are going to explain what reflection is in general and how can be used in Java. Real uses cases about different reflection uses are listed in the next chapters.

Several code snippets will be shown; at the end of this article you can find a compressed file that contains all these examples (and some more).

All code has been written using Eclipse Luna 4.4 and Java update 8.25, no third party libraries are needed.

 

1. Reflection

The concept of reflection in software means the ability to inspect, analyze and modify other code at runtime. For example imagine an application that takes as input some files containing source code (we do not care about what source code yet). The goal of this application is to count the number of methods that are contained in each passed class. This can be solved using reflection by analyzing the code and counting the elements which are actually methods, ignoring other kind of elements like attributes, interfaces, etc, and grouping them by classes.

Purely speaking, this example is not really reflection, because the code does not have to be analyzed at runtime and the task can be done in any other stage, but it can be also done at runtime and then we would be actually talking about reflection.

Another example would be an application that analyzes the content of given classes and executes the methods that contain a specific annotation with arguments provided in runtime: In the Java Junit framework we have for example the annotation@Test. This is actually what Junit does; and does it using reflection.

2. Introduction to reflection in Java

In Java, it is possible to inspect fields, classes, methods, annotations, interfaces, etc. at runtime. You do not need to know how classes or methods are called, neither the parameters that are needed, all of that can be retrieved at runtime using reflection. It is also possible to instantiate new classes, to create new instances and to execute their methods, all of it using reflection.

Reflection is present in Java since the beginning of the times via its reflection API. The class Class contains all the reflection related methods that can be applied to classes and objects like the ones that allow a programmer to retrieve the class name, to retrieve the public methods of a class, etc. Other important classes are MethodField and Typecontaining specific reflection methods that we are going to see in this tutorial.

Although reflection is very useful in many scenarios, it should not be used for everything. If some operation can be executed without using reflection, then we should not use it. Here are some reasons:

  • The performance is affected by the use of reflection since all compilation optimizations cannot be applied: reflection is resolved at runtime and not at compile stages.
  • Security vulnerabilities have to be taken into consideration since the use of reflection may not be possible when running in secure contexts like Applets.
  • Another important disadvantage that is good to mention here is the maintenance of the code. If your code uses reflection heavily it is going to be more difficult to maintain. The classes and methods are not directly exposed in the code and may vary dynamically so it can get difficult to change the number of parameters that a method expects if the code that calls this method is invoked via reflection.
  • Tools that automatically refactor or analyze the code may have trouble when a lot of reflection is present.

3. Use cases

Despite all the limitations, reflection is a very powerful tool in Java that can be taken into consideration in several scenarios.

In general, reflection can be used to observe and modify the behavior of a program at runtime. Here is a list with the most common use cases:

  • IDEs can heavily make use of reflection in order to provide solutions for auto completion features, dynamic typing, hierarchy structures, etc. For example, IDEs like Eclipse or PHP Storm provide a mechanism to retrieve dynamically the arguments expected for a given method or a list of public methods starting by “get” for a given instance. All these are done using reflection.
  • Debuggers use reflection to inspect dynamically the code that is being executed.
  • Test tools like Junit or Mockito use reflection in order to invoke desired methods containing specific syntax or to mock specific classes, interfaces and methods.
  • Dependency injection frameworks use reflection to inject beans and properties at runtime and initialize all the context of an application.
  • Code analysis tools like PMD or Findbugs use reflection in order to analyze the code against the list of code violations that are currently configured.
  • External tools that make use of the code dynamically may use reflection as well.

In this tutorial we are going to see several examples of use of reflection in Java. We will see how to get all methods for a given instance, without knowing what kind of class this instance is and we are going to invoke different methods depending on their syntax.

We are not just going to show what other tutorials do, but we will go one step forward by indicating how to proceed when using reflection with generics, annotations, arrays, collections and other kind of objects. Finally we will explain the main new features coming out with Java 8 related to this topic.

4. Reflection components and mechanisms

In order to start coding and using reflection in Java we first have to explain a couple of concepts that may be relevant.

  • Interface in Java is a contract with the applications that may use them. Interfaces contain a list of methods that are exposed and that have to be implemented by the subclasses implementing these interfaces. Interfaces cannot be instantiated. Since Java 8 they can contain default method implementations although this is not the common use.
  • Class is the implementation of a series of methods and the container of a series of properties. It can be instantiated.
  • Object is an instance of a given class.
  • Method is some code performing some actions. They have return types as outputs and input parameters.
  • Field is a property of a class.
  • Enums are elements containing a set of predefined constants.
  • Private element is an element that is only visible inside a class and cannot be accessed from outside. It can be a method, a field…
  • Static elements are elements that belong to the class and not to a specific instance. Static elements can be fields used across all instances of a given class, methods that can be invoked without need to instantiate the class, etc. This is very interesting while using reflection since it is different to invoke a static method than a non static one where you need an instance of a class to execute it.
  • Annotation is code Meta data informing about the code itself.
  • Collection is a group of elements, can be a List, a Map, a Queue, etc.
  • Array is an object containing a fixed number of values. Its length is fixed and is specified on creation.
  • Dynamic proxy is a class implementing a list of interfaces specified at runtime. They use the classjava.lang.reflect.Proxy. We will see this more in detail in the next chapters.
  • Class loader is an object in charge of loading classes given the name of a class. In Java, every class provide methods to retrieve the class loader: Class.getClassLoader().
  • Generics were introduced in java update 5. They offer compile time safety by indicating what type or sub types a collection is going to use. For example using generics you can prevent that an application using a list containing strings would try to add a Double to the list in compile time.

The different nature of these components is important in order to use reflection within them. Is not the same to try to invoke a private method than a public one; it is different to get an annotation name or an interface one, etc. We will see examples for all of these in the next chapters.

5. Classes

Everything in Java is about classes, reflection as well. Classes are the starting point when we talk about reflection. The classjava.lang.Class contains several methods that allow programmers to retrieve information about classes and objects (and other elements) at runtime.

In order to retrieve the class information from a single instance we can write (in this case, for the String class):

1Class<? extends String> stringGetClass = stringer.getClass();

Or directly from the class name without instantiation:

1Class<String> stringclass = String.class;

or using the java.lang.Class.forName(String) method:

1Class.forName( "java.lang.String" )

From a class object we can retrieve all kind of information like declared methods, constructors, visible fields, annotations, types…In this tutorial all these is explained in the following chapters.

It is also possible to check properties for a given class like for example if a class is a primitive, or an instance:

1stringGetClass.isInstance( "dani" );
2stringGetClass.isPrimitive();

It is also possible to create new instances of a given class using the method java.lang.Class.newInstance() passing the right arguments:

1String newInstanceStringClass = stringclass.newInstance();
2 
3        String otherInstance = (String)Class.forName( "java.lang.String" ).newInstance();

The java.lang.Class.newInstance() method can be used only when the class contains a public default constructor or a constructor without arguments, if this is not the case, this method cannot be used. In these cases where thejava.lang.Class.newInstance() method cannot be used the solution is to retrieve a proper constructor at runtime and create an instance using this constructor with the arguments that it is expecting. We will see in the chapter related to constructors.

6. Interfaces

Interfaces are elements that cannot be instantiated and that contain the exposed methods that should be implemented by their subclasses. Related to reflection there is nothing special regarding interfaces.

Interfaces can be accessed like a class using their qualified name. All methods available for classes are available for interfaces as well. Here is an example of how to access interface class information at runtime:

1// can be accessed like a class
2System.out.println( "interface name: " + InterfaceExample.class.getName() );

Assuming that the InterfaceExample element is an interface.

One obvious difference between classes and interfaces is that interfaces cannot be instantiated using reflection via thenewInstance() method:

1// cannot be instantiated:  java.lang.InstantiationException
2InterfaceExample.class.newInstance();

The snippet above will throw an InstantiationException at runtime. At compile time no error appears.

7. Enums

Enums are special java types that allow variables to be a set of constants. These constants are predefined in the enum declaration:

1enum ExampleEnum
2{
3    ONE, TWO, THREE, FOUR
4};

Java contains several enums specific methods:

  • java.lang.Class.isEnum(): Returns true if the element is of the type enum. False otherwise
  • java.lang.Class.getEnumConstants(): Gets all constants for the given element (which is an enum). In case the element is not an enum an exception is thrown.
  • java.lang.reflect.Field.isEnumConstant(): Returns true in case the field used is an enum constant. False otherwise. Only applicable to fields.

We are going to see an example of how to use the main enum methods related to reflection. First of all we create an instance of the enum:

1ExampleEnum value = ExampleEnum.FOUR;

We can check if the element is an enum using the method isEnum():

1System.out.println( "isEnum " + value.getClass().isEnum() );

In order to retrieve all the enum constants we can do something like the following using the method getEnumConstants():

1ExampleEnum[] enumConstants = value.getClass().getEnumConstants();
2for( ExampleEnum exampleEnum : enumConstants )
3{
4        System.out.println( "enum constant " + exampleEnum );
5}

Finally we can check how to use the field related method isEnumConstants(). First we retrieve all declared fields for the given class (we will see more in detail in the next chapters all methods related reflection utilities) and after that we can check if the field is an enum constant or not:

1Field[] flds = value.getClass().getDeclaredFields();
2for( Field f : flds )
3{
4    // check for each field if it is an enum constant or not
5    System.out.println( f.getName() + " " + f.isEnumConstant() );
6}

The output of all these pieces of code will be something like the following:

01isEnum true
02enum constant ONE
03enum constant TWO
04enum constant THREE
05enum constant FOUR
06ONE true
07TWO true
08THREE true
09FOUR true
10ENUM$VALUES false

The string ENUM$VALUES false refers to the internal enum values field. For more information about enums and how to handle them, please visit http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html.

8. Primitive types

In Java, there are a couple of types that are handled differently because of its nature and behavior: when we are talking about reflection, primitive types like int, float, double, etc. can be accessed and used almost like any other classes.
Here are a couple of examples of how to use reflection when we are working with primitive types:

• It is possible to retrieve a class object from a primitive type as for any other non primitive type:

1Class<Integer> intClass = int.class;

• But It is not possible to create new instances for primitive types using reflection:

1Integer intInstance = intClass.newInstance();

• It is possible to check if a given class belongs to a primitive type or not using the methodjava.lang.Class.isPrimitive():

1System.out.println( "is primitive: " + intClass.isPrimitive() );

In this case an exception of the type java.lang.InstantiationException is going to be thrown.

9. Fields

Class fields can be handled in runtime using reflection. Classes offer several methods to access their fields at runtime. The most important ones are:
• java.lang.Class.getDeclaredFields(): It returns an array with all declared fields for the class. It returns all private fields as well.
• java.lang.Class.getFields(): It returns an array with all accessible fields for the class.
• java.lang.Class.getField(String): It returns a field with the name passed as parameter. It throws an exception if the field does not exist or is not accessible.
• java.lang.Class.getDeclaredFields(): It returns a field with the given name, if the field does not exist it throws an exception.
These methods return an array of elements (or a single one) of the type java.lang.reflect.Field. This class contains several interesting methods that can be used at runtime that allow a programmer to read the properties and the values of the specific field.

Here is a class that uses this functionality:

01String stringer = "this is a String called stringer";
02 
03Class<? extends String> stringGetClass = stringer.getClass();
04 
05Class<String> stringclass = String.class;
06 
07Field[] fields = stringclass.getDeclaredFields();
08 
09for( Field field : fields )
10{
11System.out.println( "*************************" );
12System.out.println( "Name: " + field.getName() );
13System.out.println( "Type: " + field.getType() );
14 
15// values
16if( field.isAccessible() )
17{
18    System.out.println( "Get: " + field.get( stringer ) );
19    // depending on the type we can access the fields using these methods
20    // System.out.println( "Get boolean: " + field.getBoolean( stringer ) );
21    // System.out.println( "Get short: " + field.getShort( stringer ) );
22    // ...
23}
24System.out.println( "Modifiers:" + field.getModifiers() );
25System.out.println( "isAccesible: " + field.isAccessible() );
26 
27}
28 
29// stringclass.getField( "hashCode" );//exception
30 
31Field fieldHashCode = stringclass.getDeclaredField( "hash" );// all fields can be
32                                                         // accessed this way
33 
34// fieldHashCode.get( stringer ); // this produces an java.lang.IllegalAccessException
35 
36// we change the visibility
37fieldHashCode.setAccessible( true );
38 
39// and we can access it
40Object value = fieldHashCode.get( stringer );
41int valueInt = fieldHashCode.getInt( stringer );
42System.out.println( value );
43 
44System.out.println( valueInt );

In the snippet shown above you can see that the Field contains several methods to get the values of a given field likeget() or type specific ones like getInt(). We also can see in the pasted code how we can change the way the visibility of a given field by using the method setAccessible().

This is not always possible and under specific conditions and environments may be prevented. However this allows us to make a private field accessible and access its value and properties via reflection. This is very useful in testing frameworks like Mockito or PowerMock.

The output or the program would be:

01*************************
02Name: value
03Type: class [C
04Modifiers:18
05isAccesible: false
06*************************
07Name: hash
08Type: int
09Modifiers:2
10isAccesible: false
11*************************
12Name: serialVersionUID
13Type: long
14Modifiers:26
15isAccesible: false
16*************************
17Name: serialPersistentFields
18Type: class [Ljava.io.ObjectStreamField;
19Modifiers:26
20isAccesible: false
21*************************
22Name: CASE_INSENSITIVE_ORDER
23Type: interface java.util.Comparator
24Modifiers:25
25isAccesible: false
260
270

10. Methods

In order to retrieve all visible methods for a given class we can do the following:

1Class<String> stringclass = String.class;
2Method[] methods = stringclass.getMethods();

Using the method java.lang.Class.getMethods() all visible or accessible methods for a given class are retrieved.
We can also retrieve an specific method using its name and the type of the arguments he is expecting to receive, as an example:

1Method methodIndexOf = stringclass.getMethod( "indexOf", String.class );

For a given method (an instance of the type java.lang.reflect.Method), we can access all its properties. The following snippet shows a couple of them like name, default values, return type, modifiers, parameters, parameter types or the exceptions thrown, we can also check if a method is accessible or not:

01// All methods for the String class
02for( Method method : methods )
03{
04System.out.println( "****************************************************" );
05System.out.println( "name: " + method.getName() );
06System.out.println( "defaultValue: " + method.getDefaultValue() );
07 
08System.out.println( "generic return type: " + method.getGenericReturnType() );
09System.out.println( "return type: " + method.getReturnType() );
10 
11System.out.println( "modifiers: " + method.getModifiers() );
12 
13// Parameters
14Parameter[] parameters = method.getParameters();
15System.out.println( parameters.length + " parameters:" );
16// also method.getParameterCount() is possible
17for( Parameter parameter : parameters )
18{
19    System.out.println( "parameter name: " + parameter.getName() );
20    System.out.println( "parameter type: " + parameter.getType() );
21}
22Class<?>[] parameterTypes = method.getParameterTypes();
23System.out.println( parameterTypes.length + " parameters:" );
24for( Class<?> parameterType : parameterTypes )
25{
26    System.out.println( "parameter type name: " + parameterType.getName() );
27}
28 
29// Exceptions
30Class<?>[] exceptionTypes = method.getExceptionTypes();
31System.out.println( exceptionTypes.length + " exception types: " );
32for( Class<?> exceptionType : exceptionTypes )
33{
34    System.out.println( "exception name " + exceptionType.getName() );
35}
36 
37System.out.println( "is accesible: " + method.isAccessible() );
38System.out.println( "is varArgs: " + method.isVarArgs() );
39 
40}

It is also possible to instantiate given methods for specific objects passing the arguments that we want, we should assure that the amount and type of the arguments is correct:

1Object indexOf = methodIndexOf.invoke( stringer, "called" );

This last feature is very interesting when we want to execute specific methods at runtime under special circumstances. Also in the creation of Invocation handlers for dynamic proxies is very useful, we will see this point at the end of the tutorial.

11. Constructors

Constructors can be used via reflection as well. Like other class methods they can be retrieved in runtime and several properties can be analyzed and checked like the accessibility, the number of parameters, their types, etc.

In order to retrieve all visible constructors from a class, we can do something like:

1// get all visible constructors
2Constructor<?>[] constructors = stringGetClass.getConstructors();

In the snippet above we are retrieving all visible constructors. If we want to get all the constructors, including the private ones, we can do something like:

1//all constructors
2Constructor<?>[] declaredConstructors =   stringclass.getDeclaredConstructors();

General information about constructors such as parameters, types, names, visibility, annotations associated, etc. can be retrieved in the following way:

01for( Constructor<?> constructor : constructors )
02{
03    int numberParams = constructor.getParameterCount() ;
04    System.out.println( "constructor " + constructor.getName() );
05    System.out.println( "number of arguments " + numberParams);
06    // public, private, etc.
07    int modifiersConstructor = constructor.getModifiers();
08    System.out.println( "modifiers " + modifiersConstructor );
09    // array of parameters, more info in the methods section
10    Parameter[] parameters = constructor.getParameters();
11    // annotations array, more info in the annotations section
12    Annotation[] annotations = constructor.getAnnotations();
13 
14}

Constructors can also be used to create new instances. This may be very useful in order to access private or not visible constructors. This should be done only under very special circumstances and depending on the system where the application is running may not work because of security reasons as explained at the beginning of this tutorial.

In order to create a new instance of a class using a specific constructor we can do something like the following:

1// can be used to create new instances (no params in this case)
2String danibuizaString = (String)constructor.newInstance(  );

In has to be taken into consideration that the amount of parameters and their type should match the constructor instance ones. Also the accessibility of the constructor has to be set to true in order to invoke it (if it was not accesible). This can be done in the same way as we did for class methods and fields.

12. Getters and Setters

Getters and setters are not different to any other class method inside a class. The main difference is that they are a standard way to access private fields.

Here is a description of both:

• Getters are used to retrieve the value of a private field inside a class. Its name starts with “get” and ends with the name of the property in camel case. They do not receive any parameter and their return type is the same than the property that they are returning. They are public.
• Setters are used to modify the value of a private field inside a class. Its name starts with “set” and ends with the name of the property in camel case. They receive one parameters of the same type than the property that they are modifying and they do not return any value (void). They are public.

For example, for the private property private int count; we can have the getter and setter methods:

1public int getCount(){
2    return this.count;
3}
4 
5public void setCount(int count){
6    this.count = count;
7}

Following these standards we can use reflection to access (read and modify) at runtime all the private properties of a class exposed via getters and setters. This mechanism is used by several known libraries like Spring Framework or Hibernate, where they expect classes to expose their properties using these kinds of methods.

Here is an example of how to use getters and setters using reflection:

01Car car = new Car( "vw touran""2010""12000" );
02 
03Method[] methods = car.getClass().getDeclaredMethods();
04 
05// all getters, original values
06for( Method method : methods )
07{
08    if( method.getName().startsWith( "get" ) )
09    {
10        System.out.println( method.invoke( car ) );
11    }
12}
13 
14// setting values
15for( Method method : methods )
16{
17 
18    if( method.getName().startsWith( "set" ) )
19    {
20        method.invoke( car, "destroyed" );
21    }
22}
23 
24// get new values
25for( Method method : methods )
26{
27    if( method.getName().startsWith( "get" ) )
28    {
29        System.out.println( method.invoke( car ) );
30    }
31}

Where the class Car. looks like the following:

01public class Car
02{
03 
04    private String name;
05    private Object price;
06    private Object year;
07 
08    public Car( String name, String year, String price )
09    {
10    this.name = name;
11    this.price = price;
12    this.year = year;
13    }
14 
15    public String getName()
16    {
17    return name;
18    }
19 
20    public void setName( String name )
21    {
22    this.name = name;
23    }
24 
25    public Object getPrice()
26    {
27    return price;
28    }
29 
30    public void setPrice( Object price )
31    {
32    this.price = price;
33    }
34 
35    public Object getYear()
36    {
37    return year;
38    }
39 
40    public void setYear( Object year )
41    {
42    this.year = year;
43    }
44 
45}

The output will be something like:

1vw touran
22010
312000
4destroyed
5destroyed
6destroyed

13. Static elements

Static classes, methods and fields behave completely different than instance ones. The main reason is that they do not need to be instantiated or created before they are invoked. They can be used without previous instantiation.

This fact changes everything: static methods can be invoked without instantiating their container classes, static class fields are stateless (so thread safe), static elements are very useful in order to create singletons and factories… Summarizing, static elements are a very important mechanism in Java.

In this chapter we are going to show the main differences between static and instance elements in relation to reflection: How to create static elements at runtime and how to invoke them.

For example, for the next static inline class:

1public class StaticReflection
2{
3 
4    static class StaticExample
5    {
6    int counter;
7    }
8...

In order to retrieve static inline classes we have the following options:

1// 1 access static class
2System.out.println( "directly " + StaticExample.class.getName() );
1//2 using for name directly throws an exception
2Class<?> forname = Class.forName("com.danibuiza.javacodegeeks.reflection.StaticReflection.StaticExample" );
1//3 using $ would work but is not that nice   
2Class<?> forname = Class.forName("com.danibuiza.javacodegeeks.reflection.StaticReflection$StaticExample" );
1// 4 another way iterating through all classes declared inside this class
2Class<?>[] classes = StaticReflection.class.getDeclaredClasses();
3for( Class<?> class1 : classes )
4{
5    System.out.println( "iterating through declared classes " + class1.getName() );
6}

The main difference is that the class is contained inside another class; this has nothing to do with reflection but with the nature of inline classes.

In order to get static methods from a class, there are no differences with the access to instance ones (this applies to fields as well):

1// access static methods in the same way as instance ones
2Method mathMethod = Math.class.getDeclaredMethod( "round"double.class );

In order to invoke static methods or fields we do not need to create or specify an instance of the class, since the method (or the field) belongs to the class itself, not to a single instance:

1// methods: object instance passed can be null since method is static
2Object result = mathMethod.invoke( nullnew Double( 12.4 ) );
3 
4// static field access, instance can be null
5Field counterField = Counter.class.getDeclaredField( "counter" );
6System.out.println( counterField.get( null ) );

14. Arrays

The class java.lang.reflect.Array offers several functionalities for handling arrays; it includes various static reflective methods:

• java.lang.reflect.Array.newInstance(Class, int): Creates a new instance of an array of the type passed as parameter with the length given in the second argument. Is similar to the method with the same name in the java.lang.Class class but this one contains parameters that allows the programmer to set the type of the array and its length.
• java.lang.reflect.Array.set(Object, int, Object): Sets an element (passed index) of the given array with the object passed as argument.
• java.lang.reflect.Array.getLength(Object): Returns the length of the array as int.
• java.lang.reflect.Array.get(Object, int): Retrieves the element of the array positioned in the pased index. Returns an object.
• java.lang.reflect.Array.getInt(Object, int): Similar method for the primitive type int. Returns an int. There are methods available for all primitive types.

Here is an example of how we can use all these methods:

01// using the Array class it is possible to create new arrays passing the type and the length via reflection
02String[] strArrayOne = (String[])Array.newInstance( String.class10 );
03 
04// it contains utility methods for setting values
05Array.set( strArrayOne, 0"member0" );
06Array.set( strArrayOne, 1"member1" );
07Array.set( strArrayOne, 9"member9" );
08 
09// and for getting values as well
10System.out.println( "strArrayOne[0] : " + Array.get( strArrayOne, 0 ) );
11System.out.println( "strArrayOne[1] : " + Array.get( strArrayOne, 1 ) );
12System.out.println( "strArrayOne[3] (not initialized) : " + Array.get( strArrayOne, 3 ) );
13System.out.println( "strArrayOne[9] : " + Array.get( strArrayOne, 9 ) );
14 
15// also methods to retrieve the lenght of the array
16System.out.println( "lenght strArrayOne: " + Array.getLength( strArrayOne ) );
17 
18// primitive types work as well
19int[] intArrayOne = (int[])Array.newInstance( int.class10 );
20 
21Array.set( intArrayOne, 01 );
22Array.set( intArrayOne, 12 );
23Array.set( intArrayOne, 910 );
24 
25// and specific getters and setters for primitive types
26forint i = 0; i < Array.getLength( intArrayOne ); ++i )
27{
28    System.out.println( "intArrayOne[" + i + "] : " + Array.getInt( intArrayOne, i ) );
29}

The output of the program above would be:

01// retrieve the class from an instance
02Class<String[]> stringArrayClassUsingInstance = String[].class;
03System.out.println( "stringArrayClassUsingInstance is array: " + stringArrayClassUsingInstance.isArray() );
04 
05// using class for name and passing [I
06Class<?> intArrayUsingClassForName = Class.forName( "[I" );
07System.out.println( "intArrayUsingClassForName is array: " + intArrayUsingClassForName.isArray() );
08 
09// or [Ljava.lang.String
10Class<?> stringArrayClassUsingClassForName = Class.forName( "[Ljava.lang.String;" );
11System.out.println( "stringArrayClassUsingClassForName is array: "
12    + stringArrayClassUsingClassForName.isArray() );
13 
14// this has no much sense in my opinion since we are creating an array at runtime and
15// getting the class to create a new one...
16Class<? extends Object> stringArrayClassUsingDoubleLoop = Array.newInstance( String.class, 0 ).getClass();
17System.out.println( "stringArrayClassUsingClassForName is array: " + stringArrayClassUsingDoubleLoop.isArray() );  

The output of the snippet above would be:

1stringArrayClassUsingInstance is array: true
2intArrayUsingClassForName is array: true
3stringArrayClassUsingClassForName is array: true
4stringArrayClassUsingClassForName is array: true

15. Collections

Collections do not have many remarkable specific features related to reflection. Here is an example of how we can handle collection based elements. As already said, there are not many differences to any other Java type.

The following method prints all the class names of all elements of a collection, it previously checks if the passed element is a collection instance or not:

01private static void reflectionCollections( Object ref )
02{
03//check is collection  
04    if( ref instanceof Collection )
05    {
06        System.out.println( "A collection:  " + ref.getClass().getName() );
07        @SuppressWarnings"rawtypes" )
08        // not nice
09        Iterator items = ( (Collection)ref ).iterator();
10        while( items != null && items.hasNext() )
11        {
12            Object item = items.next();
13            System.out.println( "Element of the collection:  " + item.getClass().getName() );
14        }
15    }
16    else
17    {
18        System.out.println( "Not a collection:  " + ref.getClass().getName() );
19    }
20}

In the code shown, reflection is just used to check the instance type passed as parameter and to retrieve the class names of the elements inside the collection. We can call this method in the following way using different elements (some are collection based, some not):

01Map<String, String> map = new HashMap<String, String>();
02map.put( "1""a" );
03map.put( "2""b" );
04map.put( "3""c" );
05map.put( "4""d" );
06 
07reflectionCollections( map );
08reflectionCollections( map.keySet() );
09reflectionCollections( map.values() );
10 
11List<String> list = new ArrayList<String>();
12list.add( "10" );
13list.add( "20" );
14list.add( "30" );
15list.add( "40" );
16 
17reflectionCollections( list );
18reflectionCollections( "this is an string" );

And we would get the following output:

01Not a collection:  java.util.HashMap
02A collection:  java.util.HashMap$KeySet
03Element of the collection:  java.lang.String
04Element of the collection:  java.lang.String
05Element of the collection:  java.lang.String
06Element of the collection:  java.lang.String
07A collection:  java.util.HashMap$Values
08Element of the collection:  java.lang.String
09Element of the collection:  java.lang.String
10Element of the collection:  java.lang.String
11Element of the collection:  java.lang.String
12A collection:  java.util.ArrayList
13Element of the collection:  java.lang.String
14Element of the collection:  java.lang.String
15Element of the collection:  java.lang.String
16Element of the collection:  java.lang.String
17Not a collection:  java.lang.String

16. Annotations

All annotations of a class, package, method, field, etc. can be retrieved using reflection. Annotations can be evaluated in runtime for each element and their values can be retrieved. The following snippet shows how to retrieve all annotations for a given class and how to print out their properties and values:

1Class<ReflectableClass> object = ReflectableClass.class;
2// Retrieve all annotations from the class
3Annotation[] annotations = object.getAnnotations();
4for( Annotation annotation : annotations )
5{
6System.out.println( annotation );
7}

The following example explains how to check if an element (field, method, class…) is marked with an specific annotation or not:

01// Checks if an annotation is present
02if( object.isAnnotationPresent( Reflectable.class ) )
03{
04    // Gets the desired annotation
05    Annotation annotation = object.getAnnotation( Reflectable.class );
06 
07    System.out.println( annotation + " present in class " +             object.getClass() );// java.lang.class
08    System.out.println( annotation + " present in class " +     object.getTypeName() );//   com.danibuiza.javacodegeeks.reflection.ReflectableClass
09 
10}

These snippets may be applicable to methods, fields and all elements that can be annotated.

You can find a very good article and extensive tutorial about Java annotations with several examples related to Java reflection in the following link: http://www.javacodegeeks.com/2014/11/java-annotations-tutorial.html.

17. Generics

Generics were introduced in Java in the update 5 and since then are a very important feature that helps to maintain the code clean and more usable. Parameterized elements are not different than other elements in Java, so all the topics explained in this tutorial apply to these elements as well.

Java contains specific reflection mechanisms to handle generics as well.
• It is possible to check at runtime if a specific element (class, method or field) is parameterized or not.
• It is also possible to retrieve the parameters type using reflection as well.

Here is an example of how we can do this:

01Method getInternalListMethod = GenericsClass.class.getMethod( "getInternalList"null );
02 
03// we get the return type
04Type getInternalListMethodGenericReturnType = getInternalListMethod.getGenericReturnType();
05 
06// we can check if the return type is parameterized (using ParameterizedType)
07if( getInternalListMethodGenericReturnType instanceof ParameterizedType )
08{
09    ParameterizedType parameterizedType = (ParameterizedType)getInternalListMethodGenericReturnType;
10    // we get the type of the arguments for the parameterized type
11    Type[] typeArguments = parameterizedType.getActualTypeArguments();
12    for( Type typeArgument : typeArguments )
13    {
14        // warning not nice
15        // we can work with that now
16        Class typeClass = (Class)typeArgument;
17        System.out.println( "typeArgument = " + typeArgument );
18        System.out.println( "typeClass = " + typeClass );
19    }
20}

In the code listed above we can see that the main class related to reflection and generics isjava.lang.reflect.ParameterizedType and one of its most important methodsjava.lang.reflect.ParameterizedType.getActualTypeArguments().

18. Class Loaders

Elements in Java are loaded using class loaders. Class loaders can be implemented by implementing the abstract classhttps://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html. They provide functionalities to load classes using their names as parameters. A typical mechanism for loading classes is to find in the class path the file that belongs to the given name and open it converting it into a Java class. Every system (JVM) has a default one.

In order to retrieve the systems default class loader we can do the following:

1ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

A programmer can also get the specific class loader used for loading a given class or instance. If nothing else is specified or configured, the default one is used. For example:

1ClassLoader classClassLoader = ReflectableClass.class.getClassLoader();

Using a class loader we can load classes at runtime passing as parameter the qualified name of a class, this name can be generated dynamically:

1Class<?> reflectableClassInstanceLoaded = systemClassLoader
2                .loadClass( "com.danibuiza.javacodegeeks.reflection.ReflectableClass" );

Another possibility is to to this using Class.forName() method and specify the class loader that we want to use as parameter:

1Class<?> reflectableClassInstanceForName = Class
2                .forName( "com.danibuiza.javacodegeeks.reflection.ReflectableClass"true, systemClassLoader );

For more information about class loaders in Java please visit the official API where you can find more information:https://docs.oracle.com/javase/7/docs/api/java/lansystemClassLoaderg/reflect/InvocationHandler.html

19. Dynamic Proxies

Dynamic proxies are classes that implement a list of interfaces specified at runtime, that is, specified when the class is created. We may have proxy interfaces, classes and instances as for any other java element.

Each instance of a proxy class contains an invocation handler object. An invocation handler object is an instance of a class that implements the interface https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/InvocationHandler.html.

When a proxy instance is used to invoke a given method, this one will be forwarded to the invoke method of the proxy instance invocation handler. The method (using reflection) and the expected arguments are passed to the invocation handler. The result of the original invocation is the returned result from the invocation handler. In order to explain that in an easier way we are going to show an example.

For more information about java dynamic proxies please visithttps://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html.
In this tutorial we are going to show how to create a simple proxy class and how to redirect methods through the proxy and execute the desired actions using reflection.

The main example program would look like:

1// an invocation handler for our needs
2InvocationHandler myHandler = new HandlerImpl();
3 
4// we can create dynamic proxy clases using the Proxy class
5InformationInterface proxy = InformationInterface)Proxy.newProxyInstance(InformationInterface.class.getClassLoader(), new Class[] {InformationInterface.class },  myHandler);
6 
7// all calls to the proxy will be passed to the handler -> the handler   implementation can be
8// decided on runtime as well
9System.out.println( proxy.getInfo() );

We can see that we have 3 main topics to explain here. The first one is the invocation handler; we need to create an instance of an invocation handler and implement there the actions that we should take when methods of the proxy are called and forwarded to it.
A new class implementing java.lang.reflect.InvocationHandler is created and the methodcom.danibuiza.javacodegeeks.reflection.HandlerImpl.invoke(Object, Method, Object[]) is overriden:

01public class HandlerImpl implements InvocationHandler
02{
03 
04    @Override
05    public Object invoke( Object obj, Method method, Object[] arguments ) throws Throwable
06    {
07        System.out.println( "using proxy " + obj.getClass().getName() );
08        System.out.println( "method " + method.getName() + " from interface " + method.getDeclaringClass().getName() );
09 
10        // we can check dynamically the interface and load the implementation that we want
11        if( method.getDeclaringClass().getName().equals("com.danibuiza.javacodegeeks.reflection.InformationInterface" ) )
12        {
13            InformationClass informationImpl = InformationClass.class.newInstance();
14            return method.invoke( informationImpl, arguments );
15        }
16 
17        return null;
18    }
19}

Using reflection we can take the actions that we want in the invoke() method.

The next step is to create the proxy itself. We do this by using the invocation handler instance created before and the class (and its interface) that we want to proxy.

1InformationInterface proxy = (InformationInterface)Proxy.newProxyInstance(
2InformationInterface.class.getClassLoader(), new Class[] {
3InformationInterface.class }, myHandler );

Once the proxy and invocation handler are created, we can start to use them. All methods of the proxy are going to be forwarded now to the invocation handler and will be handled there.

1//the getInfo() method will be forwarded via the invocation handler
2System.out.println( proxy.getInfo() );

This is a very simple example of dynamic proxies in Java but it explains how reflection can be used in this scenario.

20. Java 8 Reflection features

There are not many changes and enhancements in Java 8 related to reflection. The most important one is the possibility to retrieve the method parameters with their proper names. Until now it was only possible to get the parameters with the names “arg0”, “arg1”, etc. This was kind of confusing and not that clean to work with.

Here is an example:

01Class<String> stringClass = String.class;
02for( Method methodStringClass : stringClass.getDeclaredMethods() )
03{
04    System.out.println( "method " + methodStringClass.getName() );
05    for( Parameter paramMethodStringClass :     methodStringClass.getParameters() )
06    {
07        // arg0, arg1, etc because the eclipse compiling tool (different    than javac) does
08        // not support -parameters option yet
09        System.out.println( " parameter name " +    paramMethodStringClass.getName() );
10        System.out.println( " parameter type " +    paramMethodStringClass.getType() );
11    }
12}

The mentioned method is java.lang.reflect.Executable.getParameters().

It has to be mentioned that in order to get this feature working you need to compile your application with the javac argument -parameters:

1javac -parameters <class>

Or using maven you should pass this parameter in the pom.xml file:

01<plugin>
02    <groupId>org.apache.maven.plugins</groupId>
03    <artifactId>maven-compiler-plugin</artifactId>
04    <version>3.1</version>
05 <configuration>
06        <source>1.8</source>
07        <target>1.8</target>
08     <compilerArgument>-parameters</compilerArgument>
09 </configuration>
10</plugin>

For those using Eclipse, it has to be mentioned that Eclipse does not use javac as compiler. At the moment of writing this article, the Eclipse compiler did not support this feature, so you need to compile your sources yourself using maven, ant or any other tool.

For the ones with big interest in Java 8 Lambdas here is a white paper with extensive information about the translation of java 8 Lambdas into “normal” java, reflection is involved: http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html.

Another interesting link about the use of the getParameters() in Java 8:https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html.

21. Summary

So that’s it. In this tutorial we explained in detail what is software reflection, how it can be used in Java and under what circumstances should and should not be used.

Reflection is a mechanism that allows programmers to analyze, modify and invoke code at runtime without previously knowing exactly what code they are executing.

Different use cases and applications can fit for using reflection like auto completion features in IDEs, unit testing processors, dependency injection or code analysis tools. It can also be used in normal applications for specific tasks but it should be avoided if possible since the performance and the security of the code will be affected. The maintenance effort will be increased in case the source code contains a lot of reflection.

Reflection in Java can be used in classes, methods, packages, fields, interfaces, annotations, etc. Using reflection it is possible to create new instance of any kind of object at runtime and to check its properties and values.

Since Java 8 the method getParameters() has been slightly modified and allows programmers to retrieve the actual names of method parameters, we explained this in the Java 8 related chapter.

The intention of this tutorial is to give an introduction and a deep overview of all the possibilities that Java offers in terms of reflection. For more specific tasks that may not be covered here, please refer to the links and resources section.

All examples shown in this tutorial can be downloaded in the download section.

22. Download

This was a tutorial on Java Reflection.

Download
You can download the full source code of this tutorial here: java_reflection

23. Resources

Apart from all links listed in the article and all the examples shown, if you would like to have more theoretical information about reflection in Java you can visit:

• The reflection API. Oracle tutorial: http://docs.oracle.com/javase/tutorial/reflect/.
• Wikipedia article about reflection: http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29
• The reflection API: http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html
• Dynamic proxies: “http://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html
• Enhancements in Java 8: http://docs.oracle.com/javase/8/docs/technotes/guides/reflection/enhancements.html#a8.


출처: http://www.javacodegeeks.com/2014/11/java-reflection-api-tutorial.html?utm_content=buffera8c08&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer

반응형
Comments