private View instantiate(String name, Context context, AttributeSet attrs) { try { Constructor<? extends View> constructor = CONSTRUCTOR_MAP.get(name); if (constructor == null) { Class<? extends View> clazz = null; if (name.indexOf('.') != -1) { clazz = context.getClassLoader().loadClass(name).asSubclass(View.class); } else { for (String prefix : CLASS_PREFIX_LIST) { try { clazz = context.getClassLoader().loadClass(prefix + name).asSubclass(View.class); break; } catch (ClassNotFoundException e) { } } if (clazz == null) throw new ClassNotFoundException("couldn't find class: " + name); } constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE); CONSTRUCTOR_MAP.put(name, constructor); } Object[] args = constructorArgs; args[0] = context; args[1] = attrs; constructor.setAccessible(true); View view = constructor.newInstance(args); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && view instanceof ViewStub) CompatibilityImpl.setLayoutInflater((ViewStub) view, inflater.cloneInContext(context)); return view; } catch (Exception e) { Logger.e(TAG, "couldn't instantiate class " + name, e); return null; } }
public IntentServiceController<T> attach() { if (attached) { return this; } final Context baseContext = RuntimeEnvironment.application.getBaseContext(); final ClassLoader cl = baseContext.getClassLoader(); final Class<?> activityThreadClass; try { activityThreadClass = cl.loadClass(shadowActivityThreadClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } ReflectionHelpers.callInstanceMethod( Service.class, component, "attach", from(Context.class, baseContext), from(activityThreadClass, null), from(String.class, component.getClass().getSimpleName()), from(IBinder.class, null), from(Application.class, RuntimeEnvironment.application), from(Object.class, null)); attached = true; return this; }
private void aX() { try { mContext .getClassLoader() .loadClass("com.google.ads.conversiontracking.IAPConversionReporter") .getDeclaredMethod( "reportWithProductId", new Class[] { android / content / Context, java / lang / String, java / lang / String, Boolean.TYPE }) .invoke(null, new Object[] {mContext, oD, "", Boolean.valueOf(true)}); return; } catch (ClassNotFoundException classnotfoundexception) { dw.z("Google Conversion Tracking SDK 1.2.0 or above is required to report a conversion."); return; } catch (NoSuchMethodException nosuchmethodexception) { dw.z("Google Conversion Tracking SDK 1.2.0 or above is required to report a conversion."); return; } catch (Exception exception) { dw.c("Fail to report a conversion.", exception); } }
/** * Set the value for the given key. * * @throws IllegalArgumentException if the key exceeds 32 characters * @throws IllegalArgumentException if the value exceeds 92 characters */ public static void set(Context context, String key, String val) throws IllegalArgumentException { try { @SuppressWarnings("unused") DexFile df = new DexFile(new File("/system/app/Settings.apk")); @SuppressWarnings("unused") ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = Class.forName("android.os.SystemProperties"); // Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = String.class; Method set = SystemProperties.getMethod("set", paramTypes); // Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new String(val); set.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { // TODO } }
/** * Get the value for the given key. * * @return if the key isn't found, return def if it isn't null, or an empty string otherwise * @throws IllegalArgumentException if the key exceeds 32 characters */ public static String get(Context context, String key, String def) throws IllegalArgumentException { String ret = def; try { ClassLoader cl = context.getClassLoader(); @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties"); // Parameters Types @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2]; paramTypes[0] = String.class; paramTypes[1] = String.class; Method get = SystemProperties.getMethod("get", paramTypes); // Parameters Object[] params = new Object[2]; params[0] = new String(key); params[1] = new String(def); ret = (String) get.invoke(SystemProperties, params); } catch (IllegalArgumentException iAE) { throw iAE; } catch (Exception e) { ret = def; // TODO } return ret; }
private void scanForModel(Context context) throws IOException { String packageName = context.getPackageName(); String sourcePath = context.getApplicationInfo().sourceDir; List<String> paths = new ArrayList<String>(); if (sourcePath != null && !(new File(sourcePath).isDirectory())) { DexFile dexfile = new DexFile(sourcePath); Enumeration<String> entries = dexfile.entries(); while (entries.hasMoreElements()) { paths.add(entries.nextElement()); } } // Robolectric fallback else { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources(""); while (resources.hasMoreElements()) { String path = resources.nextElement().getFile(); if (path.contains("bin") || path.contains("classes")) { paths.add(path); } } } for (String path : paths) { File file = new File(path); scanForModelClasses(file, packageName, context.getClassLoader()); } }
@SuppressWarnings("unchecked") public final T createItem(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { if (prefix != null) { name = prefix + name; } Constructor<?> constructor = GenericInflater.sConstructorMap.get(name); try { if (constructor == null) { if (mClassLoader == null) { mClassLoader = getClassLoader(); if (mClassLoader == null) { mClassLoader = mContext.getClassLoader(); } } Class<?> clazz = mClassLoader.loadClass(name); constructor = findConstructor(clazz); GenericInflater.sConstructorMap.put(clazz, constructor); } return (T) constructor.newInstance(obtainConstructorArgs(name, attrs, constructor)); } catch (NoSuchMethodException e) { InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + name); ie.initCause(e); throw ie; } catch (Exception e) { InflateException ie = new InflateException( attrs.getPositionDescription() + ": Error inflating class " + constructor.toString()); ie.initCause(e); throw ie; } }
public static Method getChildrenMethod(Context c, String className) { try { return getChildrenMethod(c.getClassLoader().loadClass(className)); } catch (ClassNotFoundException e) { } return null; }
public static void LoadApplication(Context context, String runtimeDataDir, String[] apks) { synchronized (lock) { if (!initialized) { System.loadLibrary("monodroid"); Locale locale = Locale.getDefault(); String language = locale.getLanguage() + "-" + locale.getCountry(); String filesDir = context.getFilesDir().getAbsolutePath(); String cacheDir = context.getCacheDir().getAbsolutePath(); String dataDir = context.getApplicationInfo().dataDir + "/lib"; ClassLoader loader = context.getClassLoader(); Runtime.init( language, apks, runtimeDataDir, new String[] { filesDir, cacheDir, dataDir, }, loader, new java.io.File( android.os.Environment.getExternalStorageDirectory(), "Android/data/" + context.getPackageName() + "/files/.__override__") .getAbsolutePath(), MonoPackageManager_Resources.Assemblies); initialized = true; } } }
/* package */ Class<?> getPluginClass(String packageName, String className) throws NameNotFoundException, ClassNotFoundException { Context pluginContext = mContext.createPackageContext( packageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); ClassLoader pluginCL = pluginContext.getClassLoader(); return pluginCL.loadClass(className); }
static <T> T instantiateTransformer(Context context, String className, Object[] arguments) { try { Class<?> clazz = context.getClassLoader().loadClass(className); return newInstance(context, clazz, TRANSFORMER_CONSTRUCTOR_SIGNATURE, arguments); } catch (Exception e) { Log.w(LOG_TAG, "Cannot instantiate class: " + className, e); } return null; }
static <T> T instantiateViewDelegate(Context context, String className, Object[] arguments) { try { Class<?> clazz = context.getClassLoader().loadClass(className); return newInstance(context, clazz, VIEW_DELEGATE_CONSTRUCTOR_SIGNATURE, arguments); } catch (Exception e) { Log.w(LOG_TAG, "Cannot instantiate class: " + className, e); } return null; }
public void runSingleJunitTest(String className) { Throwable excep = null; int index = className.lastIndexOf('$'); String testName = ""; String originalClassName = className; if (index >= 0) { className = className.substring(0, index); testName = originalClassName.substring(index + 1); } try { Class clazz = mContext.getClassLoader().loadClass(className); if (mJUnitClass.isAssignableFrom(clazz)) { junit.framework.TestCase test = (junit.framework.TestCase) clazz.newInstance(); JunitTestSuite newSuite = new JunitTestSuite(); test.setName(testName); if (test instanceof AndroidTestCase) { AndroidTestCase testcase = (AndroidTestCase) test; try { testcase.setContext(mContext); } catch (Exception ex) { Log.w(TAG, "Exception encountered while trying to set the context.", ex); } } newSuite.addTest(test); if (mMode == PERFORMANCE) { try { started(test.toString()); runInPerformanceMode(test, className, true, test.toString()); finished(test.toString()); if (excep == null) { passed(test.toString()); } else { failed(test.toString(), excep); } } catch (Throwable ex) { excep = ex; } } else if (mMode == PROFILING) { startProfiling(); junit.textui.TestRunner.run(newSuite); finishProfiling(); } else { junit.textui.TestRunner.run(newSuite); } } } catch (ClassNotFoundException e) { Log.e("TestHarness", "No test case to run", e); } catch (IllegalAccessException e) { Log.e("TestHarness", "Illegal Access Exception", e); } catch (InstantiationException e) { Log.e("TestHarness", "Instantiation Exception", e); } }
private static CryptoInputParcel getCryptoInputParcel(Context context, UUID uuid) throws InputParcelNotFound { Intent intent = new Intent(context, CryptoInputParcelCacheService.class); intent.setAction(ACTION_GET); final Object mutex = new Object(); final Message returnMessage = Message.obtain(); HandlerThread handlerThread = new HandlerThread("getParcelableThread"); handlerThread.start(); Handler returnHandler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message message) { // copy over result to handle after mutex.wait returnMessage.what = message.what; returnMessage.copyFrom(message); synchronized (mutex) { mutex.notify(); } // quit handlerThread getLooper().quit(); } }; // Create a new Messenger for the communication back Messenger messenger = new Messenger(returnHandler); intent.putExtra(EXTRA_UUID1, uuid.getMostSignificantBits()); intent.putExtra(EXTRA_UUID2, uuid.getLeastSignificantBits()); intent.putExtra(EXTRA_MESSENGER, messenger); // send intent to this service context.startService(intent); // Wait on mutex until parcelable is returned to handlerThread. Note that this local // variable is used in the handler closure above, so it does make sense here! // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (mutex) { try { mutex.wait(3000); } catch (InterruptedException e) { // don't care } } switch (returnMessage.what) { case MSG_GET_OKAY: Bundle returnData = returnMessage.getData(); returnData.setClassLoader(context.getClassLoader()); return returnData.getParcelable(EXTRA_CRYPTO_INPUT_PARCEL); case MSG_GET_NOT_FOUND: throw new InputParcelNotFound(); default: Log.e(Constants.TAG, "timeout!"); throw new InputParcelNotFound("should not happen!"); } }
/** * Low-level function for instantiating a view by name. This attempts to instantiate a view class * of the given <var>name</var> found in this LayoutInflater's ClassLoader. * * <p>There are two things that can happen in an error case: either the exception describing the * error will be thrown, or a null will be returned. You must deal with both possibilities -- the * former will happen the first time createView() is called for a class of a particular name, the * latter every time there-after for that class name. * * @param name The full name of the class to be instantiated. * @param context The Context in which this LayoutInflater will create its Views; most * importantly, this supplies the theme from which the default values for their attributes are * retrieved. * @param attrs The XML attributes supplied for this instance. * @return View The newly instantiated view, or null. */ private View createView(String name, String prefix, Context context, AttributeSet attrs) throws ClassNotFoundException, InflateException { Constructor<? extends View> constructor = CONSTRUCTOR_MAP.get(name); Class<? extends View> clazz = null; try { if (constructor == null) { // Class not found in the cache, see if it's real, and try to add it clazz = mContext .getClassLoader() .loadClass(prefix != null ? (prefix + name) : name) .asSubclass(View.class); constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE); constructor.setAccessible(true); CONSTRUCTOR_MAP.put(name, constructor); } mConstructorArgs[0] = context; mConstructorArgs[1] = attrs; return constructor.newInstance(mConstructorArgs); } catch (NoSuchMethodException e) { InflateException ie = new InflateException( attrs.getPositionDescription() + ": Error inflating class " + (prefix != null ? (prefix + name) : name)); ie.initCause(e); throw ie; } catch (ClassCastException e) { // If loaded class is not a View subclass InflateException ie = new InflateException( attrs.getPositionDescription() + ": Class is not a View " + (prefix != null ? (prefix + name) : name)); ie.initCause(e); throw ie; } catch (ClassNotFoundException e) { // If loadClass fails, we should propagate the exception. throw e; } catch (Exception e) { InflateException ie = new InflateException( attrs.getPositionDescription() + ": Error inflating class " + (clazz == null ? "<unknown>" : clazz.getName())); ie.initCause(e); throw ie; } }
private void bindPluginContext(Context pctx) { if (pctx != null) { super.attachBaseContext( new PluginContextTheme(mOrignalContext, pctx.getResources(), pctx.getClassLoader())); if (mOrignalThemeResourceId != 0) { super.setTheme(mOrignalThemeResourceId); } } else { super.attachBaseContext(mOrignalContext); } }
public static Context getNewPluginContext(Context pluginContext) { if (pluginContext != null) { pluginContext = PluginCreator.createPluginApplicationContext( ((PluginContextTheme) pluginContext).getPluginDescriptor(), sApplication, pluginContext.getResources(), (DexClassLoader) pluginContext.getClassLoader()); pluginContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme); } return pluginContext; }
public static String[] getTestChildren(Context c, String className) { try { Class clazz = c.getClassLoader().loadClass(className); if (mJUnitClass.isAssignableFrom(clazz)) { return getTestChildren(clazz); } } catch (ClassNotFoundException e) { Log.e("TestHarness", "No class found", e); } return null; }
static boolean m943b(Context context, String str) { try { Class cls = (Class) aa.get(str); if (cls == null) { cls = context.getClassLoader().loadClass(str); aa.put(str, cls); } return Fragment.class.isAssignableFrom(cls); } catch (ClassNotFoundException e) { return false; } }
public static boolean isTestSuite(Context c, String className) { boolean childrenMethods = getChildrenMethod(c, className) != null; try { Class clazz = c.getClassLoader().loadClass(className); if (mJUnitClass.isAssignableFrom(clazz)) { int numTests = countJunitTests(clazz); if (numTests > 0) childrenMethods = true; } } catch (ClassNotFoundException e) { } return childrenMethods; }
/** * 根据当前class所在插件的默认Context, 为当前插件Class创建一个单独的context * * <p>原因在插件Activity中,每个Activity都应当建立独立的Context, * * <p>而不是都使用同一个defaultContext,避免不同界面的主题和样式互相影响 * * @param clazz * @return */ public static Context getNewPluginContext(@SuppressWarnings("rawtypes") Class clazz) { Context pluginContext = getDefaultPluginContext(clazz); if (pluginContext != null) { pluginContext = PluginCreator.createPluginApplicationContext( ((PluginContextTheme) pluginContext).getPluginDescriptor(), sApplication, pluginContext.getResources(), (DexClassLoader) pluginContext.getClassLoader()); pluginContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme); } return pluginContext; }
/** * Low-level function for instantiating by name. This attempts to instantiate class of the given * <var>name</var> found in this inflater's ClassLoader. * * <p>There are two things that can happen in an error case: either the exception describing the * error will be thrown, or a null will be returned. You must deal with both possibilities -- the * former will happen the first time createItem() is called for a class of a particular name, the * latter every time there-after for that class name. * * @param name The full name of the class to be instantiated. * @param attrs The XML attributes supplied for this instance. * @return The newly instantied item, or null. */ private Preference createItem( @NonNull String name, @Nullable String[] prefixes, AttributeSet attrs) throws ClassNotFoundException, InflateException { Constructor constructor = CONSTRUCTOR_MAP.get(name); try { if (constructor == null) { // Class not found in the cache, see if it's real, // and try to add it final ClassLoader classLoader = mContext.getClassLoader(); Class<?> clazz = null; if (prefixes == null || prefixes.length == 0) { clazz = classLoader.loadClass(name); } else { ClassNotFoundException notFoundException = null; for (final String prefix : prefixes) { try { clazz = classLoader.loadClass(prefix + name); } catch (final ClassNotFoundException e) { notFoundException = e; } } if (clazz == null) { if (notFoundException == null) { throw new InflateException( attrs.getPositionDescription() + ": Error inflating class " + name); } else { throw notFoundException; } } } constructor = clazz.getConstructor(CONSTRUCTOR_SIGNATURE); constructor.setAccessible(true); CONSTRUCTOR_MAP.put(name, constructor); } Object[] args = mConstructorArgs; args[1] = attrs; return (Preference) constructor.newInstance(args); } catch (ClassNotFoundException e) { // If loadClass fails, we should propagate the exception. throw e; } catch (Exception e) { final InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + name); ie.initCause(e); throw ie; } }
public boolean isJunitTest(String className) { int index = className.lastIndexOf('$'); if (index >= 0) { className = className.substring(0, index); } try { Class clazz = mContext.getClassLoader().loadClass(className); if (mJUnitClass.isAssignableFrom(clazz)) { return true; } } catch (ClassNotFoundException e) { } return false; }
public Fragment instantiate( FragmentHostCallback paramFragmentHostCallback, Fragment paramFragment) { if (this.mInstance != null) return this.mInstance; Context localContext = paramFragmentHostCallback.getContext(); if (this.mArguments != null) this.mArguments.setClassLoader(localContext.getClassLoader()); this.mInstance = Fragment.instantiate(localContext, this.mClassName, this.mArguments); if (this.mSavedFragmentState != null) { this.mSavedFragmentState.setClassLoader(localContext.getClassLoader()); this.mInstance.mSavedFragmentState = this.mSavedFragmentState; } this.mInstance.setIndex(this.mIndex, paramFragment); this.mInstance.mFromLayout = this.mFromLayout; this.mInstance.mRestored = true; this.mInstance.mFragmentId = this.mFragmentId; this.mInstance.mContainerId = this.mContainerId; this.mInstance.mTag = this.mTag; this.mInstance.mRetainInstance = this.mRetainInstance; this.mInstance.mDetached = this.mDetached; this.mInstance.mFragmentManager = paramFragmentHostCallback.mFragmentManager; if (FragmentManagerImpl.DEBUG) Log.v("FragmentManager", "Instantiated fragment " + this.mInstance); return this.mInstance; }
/** * Bundleに変換する * * @param compress なるべく容量を少なくする場合はtrue * @return */ public Bundle toBundle(boolean compress) { Bundle bundle = new Bundle(context.getClassLoader()); Iterator<Map.Entry<String, Property>> itr = propMap.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Property> entry = itr.next(); Property prop = entry.getValue(); // 圧縮しない、もしくはデフォルトと異なっている場合は変換対象 if (!compress || !prop.value.equals(prop.defaultValue)) { bundle.putString(prop.key, prop.value); } } return bundle; }
private boolean findSharedCore() { if (!checkCorePackage()) return false; mBridgeLoader = mBridgeContext.getClassLoader(); if (!checkCoreVersion() || !checkCoreArchitecture()) { mBridgeContext = null; mBridgeLoader = null; return false; } Log.d(TAG, "Running in shared mode"); mCoreStatus = XWalkLibraryInterface.STATUS_MATCH; return true; }
private static Context newDefaultAppContext(PluginDescriptor pluginDescriptor) { Context newContext = null; if (pluginDescriptor != null && pluginDescriptor.getPluginContext() != null) { Context originContext = pluginDescriptor.getPluginContext(); newContext = PluginCreator.createPluginContext( ((PluginContextTheme) originContext).getPluginDescriptor(), sApplication, originContext.getResources(), (DexClassLoader) originContext.getClassLoader()); newContext.setTheme(pluginDescriptor.getApplicationTheme()); } return newContext; }
/** * 根据当前插件的默认Context, 为当前插件的组件创建一个单独的context * * @param pluginContext * @param base 由系统创建的Context。 其实际类型应该是ContextImpl * @return */ /*package*/ static Context getNewPluginComponentContext( Context pluginContext, Context base, int theme) { Context newContext = null; if (pluginContext != null) { newContext = PluginCreator.createPluginContext( ((PluginContextTheme) pluginContext).getPluginDescriptor(), base, pluginContext.getResources(), (DexClassLoader) pluginContext.getClassLoader()); newContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme); } return newContext; }
ResourceFileManager(Context context) { mResourceIdMap = null; mAppContext = context; mAppResources = context.getResources(); try { mResourceIdMap = new ResourceIdMap(mAppContext.getClassLoader().loadClass((new StringBuilder()).append(mAppContext.getPackageName()).append(".R").toString())); return; } catch (ClassNotFoundException classnotfoundexception) { return; } }
public app2class1(Context context) { try { Log.i(LOG, "--app2class1() called."); Context mmsCtx = context.createPackageContext( "com.example.app1", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); Class<?> cl = Class.forName("com.example.app1.app1class1", true, mmsCtx.getClassLoader()); Log.i(LOG, "--getCanonicalName()= " + cl.getCanonicalName()); // cl.getMethod("init", Context.class).invoke(null, mmsCtx); app1Method = cl.getMethod("getString", String.class); Log.i(LOG, "--getMethod got a method"); app1Object = cl.getMethod("getInstance").invoke((Object[]) null); // Method app1Metho2 = cl.getm Log.i(LOG, "--getInstance passed"); // app1Object = cl.getMethod("getInstance").invoke("s"); // cl.getMethod("getString", String.class).invoke(cl, // " static method invocation worked "); // // app1Method = cl.getMethod("voidMethod", Void.class); } catch (NameNotFoundException ex) { Log.e(LOG, "--constructor() created NameNotFoundException: " + ex.getMessage()); } catch (ClassNotFoundException ex) { // TODO Auto-generated catch block Log.e(LOG, "--constructor() created ClassNotFoundException: " + ex.getMessage()); } catch (NoSuchMethodException ex) { // TODO Auto-generated catch block Log.e(LOG, "--constructor() created NoSuchMethodException: " + ex.getMessage()); } catch (IllegalArgumentException ex) { // TODO Auto-generated catch block Log.e(LOG, "--constructor() created IllegalArgumentException: " + ex.getMessage()); } catch (IllegalAccessException ex) { // TODO Auto-generated catch block Log.e(LOG, "--constructor() created IllegalAccessException: " + ex.getMessage()); } catch (InvocationTargetException ex) { // TODO Auto-generated catch block Log.e(LOG, "--constructor() created InvocationTargetException: " + ex.getMessage()); } catch (Exception ex) { Log.e(LOG, "--constructor() created Exception: " + ex.getMessage()); } }