Java - Reflection (java.lang.Class)

Java Conceptuel Diagram

About

Language - Reflection in Java

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





Discover More
Card Puncher Data Processing
How to develop a Task for Ant?

How to develop a Task for Ant A class is registered as an AnT task if it's provide a method with the signature “public void execute()”. The class doesn't need to extends no superclass and...
Simple Class
Java - Class (Definition)

A java/lang/Classclass provides the blueprint for objects; you create an object from a class. All classes are derived from the Object class. A class declaration names the class and encloses the class...
Java Conceptuel Diagram
Java - Debbugers

Debuggers examine private members on classes with the reflection API.
Java Conceptuel Diagram
Java - Java API for XML Binding (JAXB) - (Un)Marshaller

API JAXB is a serialization library (Java binding tool) between XML and Object. It uses annotations to bind XML documents to a java object model. Located under the javax.xml.bind package. It generates...
Java Conceptuel Diagram
Java - Object (instance of a class)

An java/lang/Objectobject: stores its state in fields and exposes its behaviour through methods (functions in some programming languages). Methods operate on an object's internal state and serve...



Share this page:
Follow us:
Task Runner