Reflection
-
Reflection basics
java.lang.reflectpackage contains classes for examining code at runtime- It is NOT to be used by the likes of You (OR Me!!)
- allows the manipulation of code at runtime (Run Away Now!)
- only Coding Super Heros use it for arcane and dangerous purposes
- No, I am not kidding.
-
Reflection basics
java.lang.reflectpackage contains classes for examining code at runtimeConstructor,Method, andFieldclasses represent constructors, methods, and fieldsClassobjects providegetFields(),getMethods()andgetConstructors()methods
-
The Class Class
- Well, a class has to be in the Java data model, yeah?
- Used for modeling classes
- A blueprint for other Classes
- Contains info about classes
-
A Class Object
- One for every class in your program
- Used for creating objects
- Contains info about the class of object it Constructs
-
Class Object Creation
- Created by the ClassLoader
- Right Here There Be Dragons
- Created on first reference of a static member of the class
-
Getting a Class object
Object.getClass()on an instance of the desired class- Class literal (eg:
Object.classorString.class) Class.forName(String className)eg:Class.forName("java.lang.String")
-
Checking the class of an object
instanceofkeyword - requires name of class at compile timeisInstance()method - allows dynamic checking- class object equality (
==or.equals())
-
Example
String str = "Hello";
If used in a conditional:
( str instanceof String ) //true
( Object.class.isInstance(str) ) // true
( str.getClass() == String.class )// true
( str.getClass() == Object.class ) // false
( str.getClass().equals(Object.class) ) //false
-
Useful Class object methods
getName(),getSimpleName(),getCanonicalName()newInstance()cast(),getSuperclass()
-