Reflection Slides
Transcript of Reflection Slides
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 1/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
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 2/36
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.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 3/36
Introduction of Java Reflection
• Java's Reflection API's makes it possible toinspect classes, interfaces, fields and methodsat 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 usingreflection.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 4/36
Java Reflection: ClassesUsing 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
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 5/36
The Class Object
Before you can do any inspection on a class youneed to obtain its java.lang.Class object.
There are two of geting Class Object:
1. If you know the name of the class at compiletime 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 atruntime, you can do like this:
• Class class = Class.forName(“Fully Qualified Name”);
• eg. Class.forName(“java.lang”);
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 6/36
Class Name
From a Class object you can obtain its name intwo versions.
1. The fully qualified class name (includingpackage name) is obtained using thegetName() 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
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 7/36
Modifiers
You can access the modifiers of a class via theClass object. You obtain the class modifiers likethis:
Class aClass = ... //obtain Class object. Seeprev. section
int modifiers = aClass.getModifiers();
The modifiers are packed into an int where eachmodifier is a flag bit that is either set or cleared.You can check the modifiers using thesemethods in the class java.lang.reflect.Modifier:
Modifier.isAbstract(int modifiers)
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 8/36
Package Info
You can obtain information about the packagefrom a Class object like this:
• Class aClass = ... //obtain Class object. See prev. Section
•
Package package = aClass.getPackage();
From the Package object you have access toinformation about the package like its name.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 9/36
Superclass
From the Class object you can access thesuperclass of the class. Here is how:
• Class superclass = aClass.getSuperclass();
The superclass class object is a Class object likeany other, so you can continue doing classreflection on that too.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 10/36
Implemented Interfaces
It is possible to get a list of the interfacesimplemented 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.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 11/36
Constructors
• You can access the constructors of a class likethis:
• Constructor[] constructors = aClass.getConstructors();
• Constructors are covered in more detail in thetext on Constructors.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 12/36
Methods
• You can access the methods of a class like this:
• Method[] method = aClass.getMethods();
• Methods are covered in more detail in the texton Methods.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 13/36
Annotations
• You can access the class annotations of a classlike this:
• Annotation[] annotations = aClass.getAnnotations();
• Annotations are covered in more detail in thetext on Annotations.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 14/36
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
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 15/36
Obtaining Constructor Objects
• The Constructor class is obtained from theClass object. Here is an example:
• Class aClass = ...//obtain class object
•
Constructor[] constructors = aClass.getConstructors();
• If you know the precise parameter types of theconstructor you want to access.
• This example returns the public constructor of the given class which takes a String asparameter:
• Class aClass = ...//obtain class object
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 16/36
Constructor Parameters
• You can read what parameters a givenconstructor takes like this:
• Constructor constructor = ... // obtain constructor
•
Class[] paramTypes = constructor.getParameterTypes();
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 17/36
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");
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 18/36
Java Reflection: Methods in brief
• Using Java Reflection you can inspect themethods 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 Types3. Instantiating Objects using Constructor Object
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 19/36
Obtaining Method Objects
• The Method class is obtained from the Classobject.
Here is an example:
• Class aClass = ...//obtain class object
• Method[] methods = aClass.getMethods();
Note:The Method[] array will have one Methodinstance for each public method declared in theclass.
This example returns the public methodnamed"methodName", in the given class which
takes a String as parameter:
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 20/36
Continue....
• If no method matches the given method nameand arguments, in this case String.class, aNoSuchMethodException is thrown.
•
If the method you are trying to access takes noparameters, pass null as the parameter typearray, like this:
• Class aClass = ...//obtain class object
• Method method = aClass.getMethod("methodName", null);
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 21/36
Method Parameters and ReturnTypes
• You can read what parameters a given methodtakes 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();
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 22/36
Invoking Methods using MethodObject
• 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) isnot static, you need to supply a valid MyObjectinstance.
Note: If the method is static you supply null
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 23/36
Java Reflection: Fields in brief
• Using Java Reflection you can inspect the fields(member variables) of classes and get / setthem at runtime.
•
This is done via the Java class java.lang.reflect.Field.
Here is a list of the topics covered:
1. Obtaining Field Objects2. Field Name
3. Field Type
4. Getting and Setting Field Values
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 24/36
Obtaining Field Objects
• The Field class is obtained from the Classobject.
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 toaccess, you can access it like this:
• Class aClass = MyObject.class
• Field field = aClass.getField("someField");
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 25/36
Field Name
Once you have obtained a Field instance, you canget its field name using the Field.getName()method, like this:
• Field field = ... //obtain field object
• String fieldName = field.getName();
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 26/36
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();
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 27/36
Getting and Setting Field Values
Once you have obtained a Field reference youcan 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 isused, because the someField is an instance
member of the MyObject class.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 28/36
Java Reflection: Private Fields
• To access a private field you will need to call theClass.getDeclaredField(String name) or Class.getDeclaredFields() method.
•
The methods Class.getField(String name) andClass.getFields() methods only return publicfields, so they won't work.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 29/36
Continue...
Here is a simple example of a class with a privatefield, and below that the code to access thatfield via Java Reflection:
public class PrivateObject {private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;}
}
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 30/36
Java Reflection: Annotations in brief
Using Java Reflection you can access theannotations 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
Wh t J A t ti ?
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 31/36
What are Java Annotations?
Annotations is a new feature from Java 5.
Annotations are a kind of comment or meta datayou 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)
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 32/36
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 viareflection at runtime.
• @Target(ElementType.TYPE) means that theannotation can only be used ontop of types(classes and interfaces or enumeration) You
can also specify METHOD or FIELD.
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 33/36
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. etDeclaredAnnotations
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 34/36
Continue..
You can also access a specific methodannotation 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: " +
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 35/36
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
=
8/3/2019 Reflection Slides
http://slidepdf.com/reader/full/reflection-slides 36/36
Continue....
You can also access a specific fieldannotation 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: " +