Java - Reflection (java.lang.Class)

> Procedural Languages > Java

1 - About

Advertising

3 - API

The java.lang.Class:

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

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

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

6 - Snippet

myClass.java
// 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);

7 - Documentation / Reference

Advertising
lang/java/reflection.txt · Last modified: 2018/03/09 16:27 by gerardnico