java - 创建并显示来自另一个模块的片段
问题描述
我的 App 模块包含一个名为 Z 的库,但在 ZI 中需要创建并显示 App 中定义的 Fragment 的实例,我该怎么做?
BillingFragment
我找到了这个,但问题是我在模块 Z 中时没有定义。
Class<?> class = Class.forName("example.package.BillingFragment");
Constructor<?> cons = class.getConstructor(BillingFragment.class);
BillingFragment object = (BillingFragment) cons.newInstance();
解决方案
如果您已经可以访问该片段并且您想使用公共默认无 arg 创建一个实例,constructor
您可以调用:
Constructor constructor= BillingFragment.class.getConstructor();
BillingFragment fragment = (BillingFragment)constructor.newInstance();
甚至更好地使用公共静态newInstance
方法:
Method method = BillingFragment.class.getMethod("newInstance", Class<?>... parameterTypes);
BillingFragment fragment = (BillingFragment) method.invoke(null, Object... args);
PS:您应该避免使用硬编码字符串,例如"example.package.BillingFragment"
或如果应用程序被混淆"newInstance"
,这些字符串将变得无效。否则,如果您确实需要,请记住保留类和方法名称。proguard-rules
推荐阅读
- php - 如何在php中获取年、月、周、周中的日期
- python-3.x - 这个错误“不是在字符串格式化期间转换的所有参数”是什么意思?
- verilog - 如何为多个模块编写测试平台?
- java - JavaFX JAR 工件添加媒体导致主类错误
- r - 如何在R中重新构造矩阵?
- javascript - Django响应将json设置为cookie
- java - 如何在Nodejs(如Java)中将字符串转换为字节数组
- python - 如何反转标签的 One-Hot Encoding 以评估 ML/DL 模型?
- flutter - 如何在 Flutter 中通过卡片点击打开另一个页面
- javascript - 是否有更新实时烛台图表的示例?