Vous êtes sur la page 1sur 36

What we will cover ?

Introduction to Java Reflection Classes Constructors Fields Methods Getter and Setters Private Fields and Methods Annotation Generics Arrays Dynamic Proxies

What is Reflection?
When you look in a mirror
you can see your reflection you can act on what you see for example straighten your tie.

In computer programming
reflection is way through which a program can see and manipulate itself.

Introduction of Java Reflection


Java's Reflection API's 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: Classes


Using Java Reflection you can inspect Java classes at runtime. From the classes you can obtain information about Class Name Class Modifies (public, private, synchronized etc.) Package Info Superclass Implemented Interfaces Constructors Methods Fields Annotations

The Class Object


Before you can do any inspection on a class you need to obtain its java.lang.Class object. There are two of geting Class Object: 1. If you know the name of the class at compile time you can obtain a Class object like this:
Class myObjectClass = MyObject.class

2. If you don't know the name at compile time, but have the class name as a string at runtime, you can do like this:
Class class = Class.forName(Fully Qualified Name); eg. Class.forName(java.lang);

Class Name
From a Class object you can obtain its name in two versions. 1. The fully qualified class name (including package name) is obtained using the getName() method like this:
Class aClass = ... //obtain Class object. See prev. Section String className = aClass.getName();

2. If you want the class name without the pacakge name you can obtain it using the

Modifiers
You can access the modifiers of a class via the Class object. You obtain the class modifiers like this: Class aClass = ... //obtain Class object. See prev. section int modifiers = aClass.getModifiers(); The modifiers are packed into an int where each modifier is a flag bit that is either set or cleared. You can check the modifiers using these methods in the class java.lang.reflect.Modifier: Modifier.isAbstract(int modifiers)

Package Info
You can obtain information about the package from a Class object like this:
Class aClass = ... //obtain Class object. See prev. Section Package package = aClass.getPackage();

From the Package object you have access to information about the package like its name.

Superclass
From the Class object you can access the superclass of the class. Here is how:
Class superclass = aClass.getSuperclass();

The superclass class object is a Class object like any other, so you can continue doing class reflection on that too.

Implemented Interfaces
It is possible to get a list of the interfaces implemented by a given class. Here is how:
Class aClass = ... //obtain Class object. See prev. section Class[] interfaces = aClass.getInterfaces();

A class can implement many interfaces. Therefore an array of Class is returned.

Constructors
You can access the constructors of a class like this:
Constructor[] constructors = aClass.getConstructors();

Constructors are covered in more detail in the text on Constructors.

Methods
You can access the methods of a class like this:
Method[] method = aClass.getMethods();

Methods are covered in more detail in the text on Methods.

Annotations
You can access the class annotations of a class like this:
Annotation[] annotations = aClass.getAnnotations();

Annotations are covered in more detail in the text on Annotations.

Java Reflection: Constructors in breif


Using Java Reflection you can inspect the constructors of classes and instantiate objects at runtime.

This is done via the Java class java.lang.reflect.Constructor. Here is a list of the topics covered: 1. Obtaining Constructor Objects 2. Constructor Parameters 3. Instantiating Objects using Constructor Object

Obtaining Constructor Objects


The Constructor class is obtained from the Class object. Here is an example:
Class aClass = ...//obtain class object Constructor[] constructors = aClass.getConstructors();

If you know the precise parameter types of the constructor you want to access. This example returns the public constructor of the given class which takes a String as parameter:
Class aClass = ...//obtain class object

Constructor Parameters
You can read what parameters a given constructor takes like this:
Constructor constructor = ... // obtain constructor Class[] paramTypes = constructor.getParameterTypes();

Instantiating Objects using Constructor Object You can instantiate an object like this: //get constructor that takes a String as argument
Constructor constructor = MyObject.class.getConstructor(String.class); MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");

Java Reflection: Methods in brief


Using Java Reflection you can inspect the methods of classes and invoke them at runtime. This is done via the Java class java.lang.reflect.Method. Here is a list of the topics covered: 1. Obtaining Method Objects 2. Method Parameters and Return Types 3. Instantiating Objects using Constructor Object

Obtaining Method Objects


The Method class is obtained from the Class object. Here is an example:
Class aClass = ...//obtain class object Method[] methods = aClass.getMethods();

Note:The Method[] array will have one Method instance for each public method declared in the class. This example returns the public method named"methodName", in the given class which takes a String as parameter:

Continue....
If no method matches the given method name and arguments, in this case String.class, a NoSuchMethodException is thrown. If the method you are trying to access takes no parameters, pass null as the parameter type array, like this:
Class aClass = ...//obtain class object Method method = aClass.getMethod("methodName", null);

Method Parameters and Return Types


You can read what parameters a given method takes like this:
Method method = ... // obtain method Class[] parameterTypes = method.getParameterTypes();

You can access the return type of a method like this:


Class returnType = method.getReturnType();

Invoking Methods using Method Object


You can invoke a method like this: //get method that takes a String as argument
Method method = MyObject.getClass.getMethod("methodName", String.class); Object returnValue = method.invoke(Object target, Object ... parameters)

In this example, if methodName(String.class) is not static, you need to supply a valid MyObject instance. Note: If the method is static you supply null

Java Reflection: Fields in brief


Using Java Reflection you can inspect the fields (member variables) of classes and get / set them at runtime. This is done via the Java class java.lang.reflect.Field. Here is a list of the topics covered: 1. Obtaining Field Objects 2. Field Name 3. Field Type 4. Getting and Setting Field Values

Obtaining Field Objects


The Field class is obtained from the Class object. Here is an example:
Class aClass = ...//obtain class object Field[] methods = aClass.getFields();

The Field[] array will have one Field instance for each public field declared in the class. If you know the name of the field you want to access, you can access it like this:
Class aClass = MyObject.class Field field = aClass.getField("someField");

Field Name
Once you have obtained a Field instance, you can get its field name using the Field.getName() method, like this:
Field field = ... //obtain field object String fieldName = field.getName();

Field Type
You can determine the field type (String, int etc.) of a field using the Field.getType() method:
Field field = aClass.getField("someField"); Object fieldType = field.getType();

Getting and Setting Field Values


Once you have obtained a Field reference you can get and set its values using the Field.get() and Field.set()methods, like this:
Class aClass = MyObject.class Field field = aClass.getField("someField"); MyObject objectInstance = new MyObject(); Object value = field.get(objectInstance); field.set(objetInstance, value);

In the above example an instance of MyObject is used, because the someField is an instance member of the MyObject class.

Java Reflection: Private Fields


To access a private field you will need to call the Class.getDeclaredField(String name) or Class.getDeclaredFields() method. The methods Class.getField(String name) and Class.getFields() methods only return public fields, so they won't work.

Continue...
Here is a simple example of a class with a private field, and below that the code to access that field via Java Reflection: public class PrivateObject { private String privateString = null; public PrivateObject(String privateString) { this.privateString = privateString; } }

Java Reflection: Annotations in brief


Using Java Reflection you can access the annotations attached to Java classes at runtime. Here is a list of the topics covered in this text: What are Java Annotations? Class Annotations Method Annotations Parameter Annotations Field Annotations

What are Java Annotations?


Annotations is a new feature from Java 5. Annotations are a kind of comment or meta data you can insert in your Java code. Here is an example of class annotation: @MyAnnotation(name="someName", value = "Hello World") public class TheClass { } Here is the MyAnnotation definition: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE)

Specifying a Retention Policy


The two directives in the annotation definition, @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.TYPE), specifies how the annotation is to be used. @Retention(RetentionPolicy.RUNTIME) means that the annotation can be accessed via reflection at runtime. @Target(ElementType.TYPE) means that the annotation can only be used ontop of types (classes and interfaces or enumeration) You can also specify METHOD or FIELD.

Method Annotations
Here is an example of a method with annotations: public class TheClass { @MyAnnotation(name="someName", value = "Hello World") public void doSomething(){} } You can access method annotations like this: Method method = ... //obtain method object Annotation[] annotations = method.getDeclaredAnnotations();

Continue..
You can also access a specific method annotation like this: Method method = ... // obtain method object Annotation annotation = method.getAnnotation(MyAnnotation.class); if(annotation instanceof MyAnnotation){ MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " +

Field Annotations
Here is an example of a field with annotations: public class TheClass { @MyAnnotation(name="someName", value = "Hello World") public String myField = null; } You can access field annotations like this: Field field = ... //obtain field object

Continue....
You can also access a specific field annotation like this: Field field = ... // obtain method object Annotation annotation = field.getAnnotation(MyAnnotation.class); if(annotation instanceof MyAnnotation){ MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " +

Vous aimerez peut-être aussi