Move instantiation-through-reflection method to controller

Bug: 73668763
Test: rerun robotest
Change-Id: If1b263dfd6a8c40f563ce53ce3f368aef5ca5a9f
This commit is contained in:
Fan Zhang
2018-02-21 11:28:41 -08:00
parent b297abc1fe
commit fc520ee38a
2 changed files with 44 additions and 37 deletions

View File

@@ -25,6 +25,8 @@ import com.android.settingslib.core.lifecycle.Lifecycle;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
/**
@@ -73,6 +75,44 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
protected Lifecycle mLifecycle;
/**
* Instantiate a controller as specified controller type and user-defined key.
* <p/>
* This is done through reflection. Do not use this method unless you know what you are doing.
*/
public static BasePreferenceController createInstance(Context context,
String controllerName, String key) {
try {
final Class<?> clazz = Class.forName(controllerName);
final Constructor<?> preferenceConstructor =
clazz.getConstructor(Context.class, String.class);
final Object[] params = new Object[] {context, key};
return (BasePreferenceController) preferenceConstructor.newInstance(params);
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException(
"Invalid preference controller: " + controllerName, e);
}
}
/**
* Instantiate a controller as specified controller type.
* <p/>
* This is done through reflection. Do not use this method unless you know what you are doing.
*/
public static BasePreferenceController createInstance(Context context, String controllerName) {
try {
final Class<?> clazz = Class.forName(controllerName);
final Constructor<?> preferenceConstructor = clazz.getConstructor(Context.class);
final Object[] params = new Object[] {context};
return (BasePreferenceController) preferenceConstructor.newInstance(params);
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException(
"Invalid preference controller: " + controllerName, e);
}
}
public BasePreferenceController(Context context, String preferenceKey) {
super(context);
mPreferenceKey = preferenceKey;