Java - Reflection (java.lang.Class)



The java.lang.Class:

  • provides the ability to create new classes and objects.
  • is the entry point for all of the Reflection operations.


  • 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.


  • 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.


// 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};

Documentation / Reference

Powered by ComboStrap