Reflection allows examining classes at runtime to discover methods and fields. The Class class has methods like forName() to get a Class object from a string. This allows discovering information about classes like superclasses, interfaces, methods, fields, etc. Methods can be invoked using invoke() by passing the method name as a string. Annotations can be used to add semantic information to classes and methods to provide additional meaning beyond just implementation.
2. Reflection uses the class Class
The class called Class has many methods.
ReflectUtil class demonstrates many
reflection techniques
String s = “java.util.Date”;
Class c = Class.forName(s);
3. Stuff you can discover
Super-classes and interfaces
methods
fields
parameters method need for invocation
visibility modifiers
data types of method returns
data types of fields
4. Accessors
What is an accessor?
a method that starts with “get” or “is”
It returns a property.
Customer c = new Customer();
c.getName(); // returns the name of the cust.
c.isDeadbeat(); // returns true or false
5. Mutators
What is a mutator?
A method that alters a property.
A method that starts with “set”
ReflectUtil ru = new ReflectUtil(new
java.util.Date());
ru.getWriteMethodNames();
6. How do I convert a string into a
method?
Given a class, c:
Method m = c.getMethod(s, new Class[]{});
For example
Method main = c.getMethod(“main”, new Class[]
{});
7. how do I invoke a method from a
string?
Given a static method, m, the first argument
to invoke can be null.
m.invoke(null, args);
What if you have a static method that takes no
arguments?
m.invoke(null,null);
8. Limitations
The class must be loadable
I.E., you must have access to the byte codes
Entire system works on byte code driven
methods.
This is not a source code driven mechanism
Everything is already compiled.
Class c = Class.forName(“ofijewoi”);//cnfe
9. Using Reflection
ReflectUtil ru = new ReflectUtil(o);
MethodList is used to store all the methods
and get information about them.
Class c = o.getClass(); //supported for all
objects.
10. public static void main(String args[]) {
java.util.Date date = new java.util.Date();
Class c = date.getClass();
MethodList ml = new MethodList(c);
Method mutators[] = ml.getWriteMethods();
Method accessors[] = ml.getReadMethods();
System.out.println("here comes the
mutations");
print(mutators);
System.out.println("here goes the accessors");
print(accessors);
}
12. Semantics for Java
Java Lacks Semantics
Semantics is the study of meaning
Double x; //what should x be?
What is the range on x?
Can x be zero?
Can x be negative?
How can I know?