Monday, June 18, 2012

Reflection vs introspection

  • Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.

http://java.sun.com/developer/technicalArticles/ALT/Reflection/
http://yzgrafik.ege.edu.tr/~tekrei/dosyalar/projeler/JavaReflection.pdf
http://www.slideshare.net/upen.rockin/reflection-in-java



  • In computer science, reflection is the ability of a computer program to examine (see type introspection) and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.[1]

Reflection is most commonly used in high-level virtual machine programming languages like Smalltalk and scripting languages and also in manifestly typed or statically typed programming languages such as Java, C, ML and Haskell.
http://en.wikipedia.org/wiki/Reflection_(computer_programming)




  • ReflectionApis

Reflection is a programming technique used to build code that is flexible by giving the programmer the power to modify and examine the behaviour of a program at runtime. Reflection gives the code access to internal structures of classes - constructors, fields and methods. It falls under the broad area of Metaprogramming - programs that write other programs.Reflection can be very powerful for late binding, creating new types duing run-time, examining types etc.

Reflective Languages

The concept of reflective programming was started late back in the 80's. Since then, there have been many languages that provide reflection capabilities. Reflection requires dynamic modification of the program. For this reason, compilers would have to have some metadata format to look back at it's own code. Java and C# do this through the Java virtual machine and the .NET VM respectively. On the other hand, since dynamic languages like Python and Ruby only try to interpret the code at run-time, more powerful forms of reflection can be achieved. Other languages like C, C++ lack reflection capabilities largely because of the metadata that they fail to maintain. The following are a few languages that support reflection:

   • Java
   • C#
   • Ruby
   • Smalltalk
   • Python
   • Eiffel
 
 
   Is reflection "Built-in"?
 
   Reflection naturally comes to interpreted languages. Ruby, Python, Smalltalk would not have to go out of their usual way to implement and exhibit reflective properties.
 
   Java and .NET look at the intermediate code to figure out the structure of a class and then try to add more at run-time.
   This, obviously takes a performance hit since the code cannot be compiled and optimized. Java and Microsoft .NET both have references to objects as well as built-in types. Wrappers for built-in types exist that provide reflection on primitive types.
 
   Languages like C, C++ lack reflective capabilities. They are based on the philosophy of "You don't pay for what you don't use". Maintaining information about types, methods and the like involve significant overhead. Moreover, performance can become a bottleneck, not to mention a few security concerns with reflection. C and C++ compilers optimize code to maximize performance and are not open to trade performance and overhead.
 
   If reflection is deemed necessary for such languages, there would have to be another library or a tool to take care of parsing the source code, building abstract syntax trees containing every detail of the program, build symbol tables, extract control and data flows by building a graphical representation and have custom analysers analyse this representation. The DMS Software Reengineering Toolkit is one such toolkit for C, C++ and COBOL.
 


 Java

The java virtual machine is capable of generating an instance of java.lang.Class for every object created. This Class consists of methods that can examine the properties of the object at runtime. In java, all the reference types are inherited from the Object class. The primitive types on the other hand have wrapper classes around them - for example int has the Integer class for it's wrapping. For example, to get the name of a class:



   Before using reflection, Java requires the user to import java.lang.reflect.*; This is the package that provides reflective capabilities. Java provides APIs for Retrieving class objects, Examining class modifiers and types and discovering class members. What Java lacks however is the finer granularity when compared to .NET. The Class objects that java uses tend to lose some information, for example, parameter names.

Java's reflection also includes useful methods that return classes themselves. The complete design of all the related classes can be captured using APIs such as:

    •getSuperClass()     : To return the classes' super class
    •getClasses() ;          : Return all members including inherited members
    •getEnclosingClass() : used in case of nested classes. Returns the immediate enclosing
 
 
http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2009/wiki2_5_ReflectionApis




  • In computing, type introspection is the ability for a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

Introspection should not be confused with reflection, which goes a step further and is the ability for a program to manipulate the values, meta-data, properties and/or functions of an object at runtime. Some programming languages also possess that capability.


The simplest example of type introspection in Java is the instanceof[1] operator. The instanceofoperator determines whether a particular object belongs to a particular class (or a subclass of that class, or a class that implements that interface). For instance:
if(obj instanceof Person){
   Person p = (Person)obj;
   p.walk();
}
The java.lang.Class[2] class is the basis of more advanced introspection.

For instance, if it is desirable to determine the actual class of an object (rather than whether it is a member of a particular class), Object.getClass() and Class.getName() can be used:
System.out.println(obj.getClass().getName());




http://en.wikipedia.org/wiki/Type_introspection



  • Java Reflection vs Java Introspection


"Reflection" refers to the low-level API with which you can ask "what are the methods of this class", "what parameters does this method accept", "what is the parent class of this class", and so on. "Introspection" is a higher-level concept; it generally refers to using the reflection API to learn about a class. For example, the javax.beans.Introspector class will give you the list of JavaBeans properties of a class -- i.e., the pairs of matching "Y getX()"/"void setX(Y)" methods.

Introspection is concept of querying any reference (Object) RUNTIME for its type/class /method details ..
Reflection is Java API which provides this ability .


http://www.coderanch.com/t/521121/java/java/Java-Reflection-vs-Java-Introspection




  • Reflection


    Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

Introspection

    Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's properties, events, and methods. This process controls the publishing and discovery of bean operations and properties.

Introspection uses reflection, the relationship between Introspection and Reflection can be seen as similar to JavaBeans and other Java classes.

http://stackoverflow.com/questions/2044446/java-introspection-and-reflection


  • Reflection and Introspection


The Reflection API allows Java code to examine classes and objects at run time and to dynamically access another class's methods and instance fields.

o java.lang.reflect

? i.e., The Field Class

getfields(); getfield(); set(); etc.

? i.e., The Method Class

getMethods(); getMethod(); invoke(); etc.


Reflection versus Introspection
The terms reflection and introspection are commonly interchanged because they provide very similar functionality: both allow programmatic access to a class's underlying methods and properties. The difference is that introspection, which uses the java.beans.Introspector class, provides a more JavaBean-centric view of a class. It provides a standard mechanism to learn about the properties, events, and methods of a class.

Reflection, on the other hand, is supported directly by the java.lang.Class class, and provides lower-level access to the underlying methods. In other words, reflection focuses on methods and not on class properties.
http://www.informit.com/guides/content.aspx?g=java&seqNum=362





  • Introspection Uses Reflection


Reflection and introspection are very closely related. Reflection is a low-level facility that allows the code to examine the internals of any class or object at runtime. Introspection builds on this facility and provides a more convenient interface for examining Beans. In fact, the relationship between reflection and introspection is very similar to the relationship between JavaBeans and other Java classes. JavaBeans are simply normal Java objects with certain design patterns enforced in their nomenclature. Introspection assumes these design patterns on the object that it is inspecting and uses low-level reflection to examine the object's internals.

http://www2.sys-con.com/itsg/virtualcd/java/archives/0305/sagar2/index.html

What is the difference between abstraction and encapsulation?


Abstraction focuses on the outside view of an object (i.e. the interface)
Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation


Object Oriented Programming: Abstraction Vs. Encapsulation
http://www.youtube.com/watch?v=57SIpmA3vcg

How is object completely encapsulated?


All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

What is Dynamic binding?



  • Dynamic binding is a binding in which the class association is not made until the object is created at execution time.

It is also called as Late binding.


  • difference between early and late binding



Anything that is decided by compiler while compiling can be refer to EARLY/COMPILE TIME Binding and anything that is to be decided at RUNTIME is called LATE/RUNTIME binding.

For Example,

Method Overloading and Method Overriding.

1) In Method Overloading your method calls to the methods are decided by the compiler in the sense that which function is going to be called is decided by your compiler at compile time. Hence being EARLY BINDING.

2) In method Overriding, it is decided at RUNTIME which method is going to be called. So it is reffered as LATE BINDING.

Types
Late Binding: type is unknown until the variable is exercised during run-time; usually through assignment but there are other means to coerce a type; dynamically typed languages call this an underlying feature, but many statically typed languages have some method of achieving late binding

Implemented often using [special] dynamic types, introspection/reflection, flags and compiler options, or through virtual methods by borrowing and extending dynamic dispatch

Early Binding: type is known before the variable is exercised during run-time, usually through a static, declarative means

Implemented often using standard primitive types


Lazy Loading: object initialization strategy that defers value assignment until needed; allows an object to be in an essentially valid but knowingly incomplete state and waiting until the data is needed before loading it

Eager Loading: object initialization strategy that immediately performs all value assignments in order to have all the data needed to be complete before considering itself to be in a valid state.

https://programmers.stackexchange.com/questions/200115/what-is-early-and-late-binding

What is static binding?


Static binding is a binding in which the class association is made during compile time.
This is also called as Early binding

What is a destructor?


Destructor is an operation that frees the state of an object and/or destroys the object itself.
In Java, there is no concept of destructors.
Its taken care by the JVM

What is a constructor?

Constructor is an operation that creates an object and/or initialises its state.

What is a superclass?

superclass is a class from which another class inherits

What is a subclass?

Subclass is a class that inherits from one or more classes

What is a base class?

Base class is the most generalised class in a class structure.
Most applications have such root classes.
In Java, Object is the base class for all classes.

What is an Interface?

Interface is an outside view of a class or object which emphasizes its abstraction while hiding its structure and secrets of its behaviour.