I Googled this and read the Java documentation, but I'm a bit confused. Can somebody please explain what a Context
is in plain English?
4 Answers
In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.
In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext
, JSF's FacesContext
, Spring's ApplicationContext
, Android's Context
, JNDI's InitialContext
, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.
A Context represents your environment. It represents the state surrounding where you are in your system.
For example, in web programming in Java, you have a Request, and a Response. These are passed to the service method of a Servlet.
A property of the Servlet is the ServletConfig, and within that is a ServletContext.
The ServletContext is used to tell the servlet about the Container that the Servlet is within.
So, the ServletContext represents the servlets environment within its container.
Similarly, in Java EE, you have EBJContexts that elements (like session beans) can access to work with their containers.
Those are two examples of contexts used in Java today.
Edit --
You mention Android.
Look here: http://developer.android.com/reference/android/content/Context.html
You can see how this Context gives you all sorts of information about where the Android app is deployed and what's available to it.
Simply saying, Java context means Java native
methods all together.
In next Java code two lines of code needs context: // (1)
and // (2)
import java.io.*;
public class Runner{
public static void main(String[] args) throws IOException { // (1)
File file = new File("D:/text.txt");
String text = "";
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null){ // (2)
text += line;
}
System.out.println(text);
}
}
(1) needs context because is invoked by Java native method private native void java.lang.Thread.start0();
(2) reader.readLine()
needs context because invokes Java native method public static native void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
PS.
That is what BalusC is sayed about pattern Facade more strictly.