Tuesday, April 17, 2012

What exactly is a Context in Java?


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?



Source: Tips4all

5 comments:

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

    ReplyDelete
  2. In Android, Context is the base class for Activity, Service, Application, and a few other things. A Context object is your gateway to much of the underlying Android system, including resources, system services (e.g., for locations and notifications), and the Intent message bus. Since your major components -- Activity and Service -- inherit from Context, you usually have a Context handy when you need it.

    ReplyDelete
  3. 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 JEE, 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.

    ReplyDelete
  4. That which surrounds, and gives meaning to, something else.
    (source: FOLDOC)

    ReplyDelete
  5. since you capitalized the word, I assume you are referring to the interface javax.naming.Context. A few classes implement this interface, and at its simplist description, it (generically) is a set of name/object pairs.

    ReplyDelete