code: public static BundleContext getBundleContext( final Bundle bundle )
      {
          try
          {
              // first try to find the getBundleContext method (OSGi spec >= 4.10)
              final Method method = Bundle.class.getDeclaredMethod( "getBundleContext" );
              if( !method.isAccessible() )
              {
                  method.setAccessible( true );
              }
              return (BundleContext) method.invoke( bundle );
          }
          catch( Exception e )
          {
              // then try to find a field in the bundle that looks like a bundle context
              try
              {
                  final Field[] fields = bundle.getClass().getDeclaredFields();
                  for( Field field : fields )
                  {
                      if( BundleContext.class.isAssignableFrom( field.getType() ) )
                      {
                          if( !field.isAccessible() )
                          {
                              field.setAccessible( true );
                          }
                          return (BundleContext) field.get( bundle );
                      }
                  }
              }
              catch( Exception ignore )
              {
                  // ignore
              }
          }
          // well, discovery failed
          return null;
      }
docs: Discovers the bundle context for a bundle. If the bundle is an 4.1.0 or greater bundle it should have a method
  that just returns the bundle context. Otherwise uses reflection to look for an internal bundle context.
  
  @param bundle the bundle from which the bundle context is needed
  
  @return corresponding bundle context or null if bundle context cannot be discovered