Allowing base class for ResourceBasedOverride to have Context based constructors

Bug: 330920490
Flag: None
Test: Presubmit
Change-Id: Ib4d1ef80133596a114a4fb32ea8ae918852a77f5
This commit is contained in:
Sunny Goyal
2024-04-05 00:42:00 -07:00
parent e0330e17e3
commit 9d28eee769
5 changed files with 30 additions and 21 deletions
@@ -34,16 +34,20 @@ public interface ResourceBasedOverride {
public static <T extends ResourceBasedOverride> T getObject(
Class<T> clazz, Context context, int resId) {
String className = context.getString(resId);
if (!TextUtils.isEmpty(className)) {
try {
Class<?> cls = Class.forName(className);
return (T) cls.getDeclaredConstructor(Context.class).newInstance(context);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| ClassCastException | NoSuchMethodException | InvocationTargetException e) {
boolean isOverridden = !TextUtils.isEmpty(className);
// First try to load the class with "Context" param
try {
Class<?> cls = isOverridden ? Class.forName(className) : clazz;
return (T) cls.getDeclaredConstructor(Context.class).newInstance(context);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| ClassCastException | NoSuchMethodException | InvocationTargetException e) {
if (isOverridden) {
Log.e(TAG, "Bad overriden class", e);
}
}
// Load the base class with no parameter
try {
return clazz.newInstance();
} catch (InstantiationException|IllegalAccessException e) {