IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

Say the Excel Jar files with utility methods used the application uses the methods in the Utility Class and the flow is controlled by the way the method gets called in order the get the things done.

whereas

In framework like spring the implementation is defined in XML files and by using annotation and the framework calls the methods as per defined in xml.

Without Ioc

  Application -> Methods -> Framework      

With Ioc

  Framework -> XML File ->  Method Call (or) Implementation      

Inversion of Control(IoC) Container:
Common characteristic of frameworks IOC manages java objects

  1. From instantiation to destruction through its BeanFactory.
  2. Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean’s scope, lifecycle events, and any AOP features for which it has been configured and coded.

Flow of control is “inverted” by dependency injection because you have effectively delegated dependencies to some external system

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor
{
    private SpellChecker checker;
    public TextEditor()
    {
        this.checker = new SpellChecker();
    }
}

What we’ve done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

public class TextEditor
{
    private ISpellChecker checker;
    public TextEditor(ISpellChecker checker)
    {
        this.checker = checker;
    }
}

Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We’re injecting the TextEditor with the dependency.

Without IoC: you ask for “apple”, and you are always served apple when you ask more.

With IoC:
You can ask for “fruit”. You can get different fruits each time you get served. for example, apple, orange, or water melon.

Inversion of Control, (or IoC), is about getting
freedom (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That’s what we called, “decoupled”. Good computer system discourages some very close relationship.)

flexibility (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.)

less dependency (Your partner has a job, you don’t have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)

Dependency Injection

What is Dependency

Quick Example:EMPLOYEE OBJECT WHEN CREATED,
              IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
   (if address is defines as dependency by Employee object)

Now in the above EMPLOYEE Class is dependent on ADDRESS Class.

You can not create the Address Object unless you create Employee Object

EMPLOYEE Class is dependent and ADDRESS Class is dependency

What is the purpose of DI?
With dependency injection, objects don’t define their dependencies themselves, the dependencies are injected to them as needed.The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.

How does it benefit ? The objects don’t need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.

When to use Dependency Injection
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up ‘test’ data.Dependency Injection gives you the ability to test specific units of code in isolation.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It’s a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g Spring) to do that, but they certainly aren’t required.

Example
A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object

Without Dependency Injection (DI):

class Car
{
  private Wheel wh   = new ApolloWheel();
  private Battery bt = new ExideBattery();

  //The rest
}

Here, the Car object is responsible for creating the dependent objects.

What if we want to change the type of its dependent object – say Wheel – after the initial ApolloWheel() punctures? We need to recreate the Car object with its new dependency say SpareWheel(), but only the Car manufacturer can do that.

Then what does the Dependency Injection do us for…?

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

After using dependency injection:

class Car
{
  private Wheel wh   = [Inject an Instance of Wheel at runtime];
  private Battery bt = [Inject an Instance of Battery at runtime];

  Car(Wheel wh,Battery bt) 
  {
      this.wh = wh;
      this.bt = bt;
  }

  //Or we can have setters
  void setWheel(Wheel wh) 
  {
      this.wh = wh;
  }
}

Lets take the below example

public class Foo
{
    private Bar _bar;

    public Foo(Bar bar)
    {
        _bar = bar;
    }

    public bool IsPropertyOfBarValid()
    {
        return _bar.SomeProperty == PropertyEnum.ValidProperty;
    }
}

without dependency injection the Bar object is dependent and tightly coupled with Foo class like below

public class Foo
{
    private Bar _bar = new Bar();
    .
    . 
}

But by using dependency injection like before code you can mock the Bar Object at runtime and call the IsPropertyOfBarValid() method over it.

  1. The Way aspect function calls are made are through proxy classes internally
  2. Internally the Spring framework creates proxy classed and calls to the code generated as per the xml are run in proxy class methods before the actual class are called
  3. In the below example in DrawingApp.java I try to create a object for the class circle by invoking factoryService getBean Method
  4. This method returns a Object of class ShapeServiceProxy with the custom methods for xml code added

ShapeService.java

package com.mugil.shapes;

public class ShapeService {
	private Circle objCircle;
	private Triangle objTriangle;
		
	public Circle getObjCircle() {
		return objCircle;
	}
	public void setObjCircle(Circle objCircle) {
		this.objCircle = objCircle;
	}
	public Triangle getObjTriangle() {
		return objTriangle;
	}
	public void setObjTriangle(Triangle objTriangle) {
		this.objTriangle = objTriangle;
	}	
}

ShapeServiceProxy.java

package com.mugil.shapes;

public class ShapeServiceProxy extends ShapeService {
	
	public Circle getObjCircle() {
		new LoggingAspect().getLogMessage();
		return super.getObjCircle();
	}
}

DrawingApp.java

package com.mugil.shapes;

public class DrawingApp
 {
	public static void main(String[] args) 
        {
		FactoryService objFactSer = new FactoryService();
		ShapeService objSS = (ShapeService)objFactSer.getBean("ShapeService");
		objSS.getObjCircle();
	}
}

FactoryService.java

package com.mugil.shapes;

public class FactoryService {
	
	public Object getBean(String className)
	{
		if(className.equals("Circle"))
			return new Circle();
		else if(className.equals("Triangle"))
			return new Triangle();
		else if(className.equals("DrawingApp"))
			return new DrawingApp();
		else if(className.equals("ShapeService"))
			return new ShapeServiceProxy();
			
		return null;
	}
}

“Reflection” is a language’s ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java has the method getClass, which lets you determine its class even if you don’t know it at compile time (like if you declared it as Object) – this might seem trivial, but such reflection is not by default possible in less dynamic languages such as C++.

Why do we need reflection?

Reflection enables us to:

  1. Examine an object’s class at runtime
  2. Construct an object for a class at runtime
  3. Examine a class’s field and method at runtime
  4. Invoke any method of an object at runtime
  5. Change accessibility flag of Constructor, Method and Field
    etc.

Reflection is important since it lets you write programs that does not have to “know” everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lets see the simple example of forName() method.

    class Simple{}  
      
    class Test{  
     public static void main(String args[]){  
      Class c=Class.forName("Simple");  
      System.out.println(c.getName());  
     }  
    }  

For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to.

So, to give you a code example of this in Java (imagine the object in question is foo) :

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

Getting list of methods in a Class by Reflection

Method[] methods = MyObject.class.getMethods();

for(Method method : methods){
    System.out.println("method = " + method.getName());
}

Details which can be accessed by reflection

  1. Class Name
  2. Class Modifies (public, private, synchronized etc.)
  3. Package Info
  4. Implemented Interfaces
  5. Superclass
  6. Constructors
  7. Fields
  8. Methods
  9. Annotations

Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.

It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.

Drawbacks
Since everything is done at runtime optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Usage

  1. Reflection is used when it is needed to get into the other classes in deeper level. So in most of the cases, these implementors have the container-behavior. For instance, dependency injection is mostly done with the use of reflection
  2. Remote procedure calling — treat part of a message received over the network as a method name.
  3. Object-relational mappings — maintain a relationship between fields in an object and columns in a database.
  4. Interfaces with dynamically typed scripting languages — turn a string value produced by a scripting language into a reference to a field or method on an object.
  5. Serialization and deserialization — convert field names to string so you can write the object’s fields to a stream and later convert it back into an object.

One useful real-world use of reflection is when writing a framework that has to interoperate with user-defined classes, where th framework author doesn’t know what the members (or even the classes) will be. Reflection allows them to deal with any class without knowing it in advance. For instance, I don’t think it would be possible to write a complex aspect-oriented librory without reflection.

Servlet Mapping in web.xml and Junit annotations are other where reflection is used.

For example, JUnit use reflection to look through methods tagged with the @Test annotation, and then call those methods when running the unit test. (Here is a set of examples of how to use JUnit.)

For web frameworks, product developers define their own implementation of interfaces and classes and put is in the configuration files. Using reflection, it can quickly dynamically initialize the classes required.

For example, Spring uses bean configuration such as:

<bean id="someID" class="com.programcreek.Foo">
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument “com.programcreek.Foo” to instantiate that Class. It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.

The same mechanism is also used for Servlet web applications:

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.programcreek.WhyReflectionServlet</servlet-class>
<servlet>