[英]How to cast an object to a subclass of itself using the subclass's Class instance object in Java?
Let's say I have an abstract class AbstractFragment
that has a superclass Fragment
: 假设我有一个抽象类
AbstractFragment
,它具有超类Fragment
:
public abstract class AbstractFragment extends Fragment {
public abstract updateData();
public static <FragmentClass extends AbstractFragment>
ChartClass newInstance(int condition, Class<ChartClass> chartFragmentClass) {
Constructor<ChartClass> c = chartFragmentClass.getConstructor();
ChartClass fragment = c.newInstance();
Bundle args = new Bundle();
args.putInt("key", condition);
fragment.setArguments(args);
return fragment;
}
And two children of the AbstractFragment
class: 还有
AbstractFragment
类的两个孩子:
public class FirstChildFragment extends AbstractFragment {
public updateData() {}
}
public class SecondChildFragment extends AbstractFragment {
public updateData() {}
}
At runtime, depending on a condition, I want to cast a Fragment object to one of either the first or second children depending on a condition or create a new instance of the child using the static method in the abstract class (I already have this static method figured out), like so: 在运行时,根据条件,我想根据条件将Fragment对象转换为第一个或第二个子对象中的一个,或者使用抽象类中的static方法创建该子对象的新实例(我已经有了这个static方法找出来),如下所示:
void onDataLoaded(int condition) {
Fragment fragment = getChildFragmentManager()
.findFragmentById(R.id.fragment_container_dashboard_chart);
Class ChildFragmentClass;
if (condition == 0) ChildFragmentClass = FirstChildFragment.class;
else if (condition == 1) ChildFragmentClass = SecondChildFragment.class;
else throw new RuntimeException("Condition is invalid");
if (fragment.getClass().isInstance(ChildFragmentClass))
((ChildFragmentClass) fragment).updateData();
else {
ChildFragmentClass childFragment = ChildFragmentClass.newInstance(5, ChildFragmentClass);
}
}
The problem in the above code is that I don't know how to properly cast the fragment
object so that it is recognized as an instance of the ChildFragmentClass
class. 上面的代码中的问题是,我不知道如何正确地转换
fragment
对象,以便将其识别为ChildFragmentClass
类的实例。 Subsequently, that means my code that attempts to call newInstance
is also correct How do I appropriately cast fragment to the ChildFragmentClass
and be able to call the appropriate methods? 随后,这意味着我尝试调用
newInstance
代码也是正确的,如何将片段适当地转换为ChildFragmentClass
并能够调用适当的方法? I want the new instance to be an instance of either the first or second child. 我希望新实例成为第一个或第二个孩子的实例。
ChildFragmentClass is not a class it is a local variable. ChildFragmentClass不是一个类,它是一个局部变量。 You should create a new variable and assign it.
您应该创建一个新变量并进行分配。
This may help with your issues. 这可能会帮助您解决问题。
if (fragment.getClass().isInstance(AbstractFragment))
((AbstractFragment) fragment).updateData();
else {
Fragment childFragment = AbstractFragment.newInstance(5, ChildFragmentClass);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.