Java 查找在param方法中传递的对象的类型
这是一个家庭作业,我遇到了一些困难,我正在尝试创建一个基本活动,它将被我的所有活动扩展。我想创建一个方法,直接在BaseActivity中配置和显示我的片段,这样在活动中我只需传递2个参数(片段片段,int-frame布局)Java 查找在param方法中传递的对象的类型,java,android,Java,Android,这是一个家庭作业,我遇到了一些困难,我正在尝试创建一个基本活动,它将被我的所有活动扩展。我想创建一个方法,直接在BaseActivity中配置和显示我的片段,这样在活动中我只需传递2个参数(片段片段,int-frame布局) public void configureAndShowFragment(BaseFragment片段,int布局){ fragment=(BaseFragment)getSupportFragmentManager().findFragmentById(布局); if(f
public void configureAndShowFragment(BaseFragment片段,int布局){
fragment=(BaseFragment)getSupportFragmentManager().findFragmentById(布局);
if(fragment==null&&findviewbyd(布局)!=null){
fragment=newfragment/您可以这样做,首先使用反射获取片段的类型,然后在无法通过ID找到它时创建
public void configureAndShowFragment(BaseFragment fragment, int layout) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (fragment == null) {
throw new RuntimeException("fragment cannot be null");
}
String fragmentClassName = fragment.getClass().getName();
fragment = (BaseFragment) getSupportFragmentManager().findFragmentById(layout);
if (fragment == null && findViewById(layout) != null) {
Class<?> clazz = Class.forName(fragmentClassName);
Constructor<?> ctor = clazz.getConstructor();
fragment = (BaseFragment) ctor.newInstance(); <== init fragment here
getSupportFragmentManager().beginTransaction()
.add(layout, fragment)
.commit();
}
}
public void configureAndShowFragment(BaseFragment fragment,int-layout)抛出ClassNotFoundException、NoSuchMethodException、IllegalAccessException、InvocationTargetException、InstantiationException{
if(片段==null){
抛出新的RuntimeException(“片段不能为null”);
}
字符串fragmentClassName=fragment.getClass().getName();
fragment=(BaseFragment)getSupportFragmentManager().findFragmentById(布局);
if(fragment==null&&findviewbyd(布局)!=null){
Class clazz=Class.forName(fragmentClassName);
Constructor=clazz.getConstructor();
fragment=(BaseFragment)ctor.newInstance();您的问题似乎很清楚,与文章的其余部分和其中的代码不同。您是否试图知道对象的类型?如果它来自基类的子类?x.getClass().getName()
获取类的名称。这是我的BaseActivity中的代码,我的其他活动将对其进行扩展并使用此方法。我想做的是能够使用将在变量fragment中传递的正确类型对其进行初始化,我不能只执行fragment=new MainFragment,因为它可以是另一个,我将有一些碎片因此必须检查它,以便我知道传递了哪个片段,并且我可以使用正确的类型初始化它。我希望您确实理解了预期的内容。感谢您的帮助。BaseFragment fragment
作为参数传递,而不是读取。顺便说一句,您想从中实例化的类类型,您应该如何知道它?在bl中条件锁定<代码>(片段==null&&findViewById(布局)!=null)
fragment为null。我在您的代码中没有看到关于该片段类型的信息建议。我添加了一个屏幕截图,希望您能有足够的细节来理解,您在第二条注释中给出的解决方案将不起作用,它将产生null指针异常,因为在我们启动该方法时,对象是空的直到null。我想知道是否有可能知道,因为在MainActivity中,将作为参数传递的主片段未启动,但它是MainFragment的一种类型,我想知道是否有任何方法可以检测到该类型,即使它尚未启动。