您可以简单地使用Class<T>.getCanonicalName()
,然后在从Bundle中读取时通过该名称实例化类。
例如,如果您想在Android组件之间进行通信,那么使用哪个单例类就可以了。
举个例子,你可以有一个动作接口
public interface Action {
void run(List<String> args, Context context);
}
应该在一个片段执行特定任务,你想用不同的成套动作进行初始化片段。然后,你的碎片的实例方法可以简单地采取Action
类作为参数:
public static void newInstance(String someParameter, Class<? extends Action>... actions) {
Bundle arguments = new Bundle();
String[] actionNames = new String[actions.length];
for (int i = 0; i < actionNames.length; i++) {
actionNames[i] = actions[i].getCanonicalName();
}
arguments.putStringArray(ARG_ACTIONS, actionNames);
}
已经定义了一些类MyActionA implements Action
和MyActionB implements Action
你将创建下列方式这些动作片段:
Fragment myFragment = MyFragment.newInstance("some parameter", MyActionA.class, MyActionB.class)
片段本身可以使用动作列表(List<Action> action
)作为成员变量,它从Bundle中初始化为onCreate()
:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (String actionName : getArguments().getStringArray(ARG_ACTIONS)) {
try {
Class<? extends Action> actionClass = (Class<? extends Action>) Class.forName(actionName);
Action action = actionClass.newInstance();
actions.put(action.getName(), action);
} catch (java.lang.InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
当试图将它们实例化为getCanonicalName()
返回null
为匿名类时,顺便说一句,这将失败与匿名类。所以这个方法不能用来传递匿名类,我怀疑这是完全可能的。
您可以尝试'putSerializable()',因为'Class'实现'Serializable',但我很怀疑你所做的是一个好主意。 – CommonsWare
您可以使用单例模式来存储和检索自定义类的实例,请查看:http://www.javaworld.com/article/2073352/core-java/simply-singleton.html –