Lab 2 : Reflection
Introduction
In this lab we will overview some of the basic principle of
reflection in Java.
Create a new project in Eclipse
tp2
for today's exercises.
Exercise 1 : A class analyzer
Start by copying the following
source into your new Eclipse project.
Exercise 1.1 : No generics version
Write a simple class analyzer. Such an analyzer expects a name of a class and it will print to the standard output its interface: its declaration, declared fields, constructors and methods.
Here is a sample output given
java.util.ArrayList
as an input:
For start do not worry about generics. There is a bonus exercise for you to do if you have enough time (meaning you have completed all the other exercises) or to do at home.
- Do not use
toString()
neither toGenericString()
method
- Try to work iteratively and test as you go
- Try to refactor as you go (hint: think about a
mkString
method that will combine an array to a String with a separator)
- The interactive behavior of the program is not very handy for testing. Think how can you speed up the development cycle (code/test).
Exercise 1.2 : Non interactive version
Modify the program so it can run non interactively taking its input from command line. For example I should be able to run it like:
$ java tp2.ClassAnalyzer java.util.Data java.util.ArrayList
Extra Exercise 1.3 : Generics version
Try to include the generics type information.
Extra Exercise 1.4 : Generics version with annotations
Try to include runtime annotations.
- Think about all the places an annotation can occur
- Print also arguments of the annotations' parameters
Extra Exercise 1.5: Global list of imports
Use only simple class names and include a list of imports right after package declaration. Think about to handle duplicates (
java.util.List
,
java.awt.List
). When you look at how Eclipse organizes the imports, it groups together same package imports, you could try to do the same.
Exercise 2 : A generic toString()
method
In the creature simulator's
AbstractCreature
class from the previous lab write a generic
toString()
method:
public String toString() {...}
which will output all of the creature's attributes (fields). It has to be generic method since subclasses of the
AbstractCreature
can define their own attributes this class is not aware of.
- Think what is the difference between
getDeclaredFields()
and getFields()
- To test it, you can add some more attributes to the
SmartCreature
Exercise 3 : Array Grow
Once you complete the method and run, you should see following output:
[1, 2, 3, 0, 0, 0]
[Maurice Chombier, Francois Pignon, null, null]
The following call will generate an exception.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ltp2.ArrayGrowTest2$Personne;
...
The nulls on the first line are fine - proving the the array has grown
- Look at the methods from the
java.util.Arrays
class.
to top