About
Language - Reflection in Java
Articles Related
API
The java.lang.Class:
- provides the ability to create new classes and objects.
- is the entry point for all of the Reflection operations.
Usage
- Extensibility Features (Plugin, …)
- Class Browsers (enumeration of the members of classes) and Visual Development Environments (to help the developer in writing correct code).
- Debuggers and Test Tools. Debuggers need to be able to examine private members on classes. Test tool can discover a set APIs defined on a class.
Disadvantage
- Performance Overhead. Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts.
- Security Restrictions. Reflection requires a runtime permission which may not be present when running under a security manager.
- Exposure of Internals. Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects. Reflective code breaks abstractions.
Snippet
// Example a class in the same package
classToInstantiate = Class.forName(myClass.class.getPackage().getName()+"."+"AName");
// Build an instance Constructor
Class[] constructorClassType = {TheReturnedInstantiateType.class};
Constructor constructor = classToInstantiate.getConstructor(constructorClassType );
// Instantiate a new instance
Object[] constructorParamValue = {The value that match the class constructor};
constructor.newInstance(constructorParamValue);
Documentation / Reference
- See also Google reflections