2015-08-31 14 views
2

是否可以在一个Bundle中放入一个Class类型?Android:如何将类类型放入一个包中?

public static <T> Intent newInstance(Class<T> EventClass) { 
    Bundle args = new Bundle(); 
    args.putXXXX(EventClass); 
    Intent intent = new Intent(MyApplication.getInstance(), MyActivity.class); 
    intent.putExtras(args); 
    return intent; 
} 

谢谢你们!

+0

您可以尝试'putSerializable()',因为'Class'实现'Serializable',但我很怀疑你所做的是一个好主意。 – CommonsWare

+0

您可以使用单例模式来存储和检索自定义类的实例,请查看:http://www.javaworld.com/article/2073352/core-java/simply-singleton.html –

回答

0

不可能将任何对象放入一个包中。您只能将两种类型放入一个包中:实现SerializableParcelable的类。

+0

实际上, 'Class'实现'Serializable'](http://developer.android.com/reference/java/lang/Class.html)。不过,我不确定它会正常工作。 – CommonsWare

+0

@CommonsWare你是对的,它应该实际上工作。但是,存储'Class'的用途是什么?我正在考虑存储该类的一个对象。而'Object'不实现'Serializable'。 – F43nd1r

+0

好吧,考虑到问题中的代码片段,我的猜测是,OP正在向一个活动发送一个'Class'来告诉它要创建什么类型的事件,其中该活动可能通过反射来创建事件对象。传递'EventClass'实例的问题是'Bundle'有效地传递值,而不是通过引用传递,这可能会阻止像匿名内部类扩展'EventClass'这样的事情。这就是说,正如我在对这个问题的评论中指出的那样,我怀疑这是一个好主意。 – CommonsWare

0

您可以简单地使用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 ActionMyActionB 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为匿名类时,顺便说一句,这将失败与匿名类。所以这个方法不能用来传递匿名类,我怀疑这是完全可能的。

相关问题