[英]Get a child class when looping through its parent class java
I am looping through my Media arraylist ArrayList that has some child classes (Audio,Video,Picture) And when I loop through my Media arraylist 我正在遍历具有一些子类(音频,视频,图片)的媒体数组列表ArrayList,并且当我遍历媒体数组列表时
public double getTotalVideoRunTime()
{
int total = 0;
for(Media v : mList)
{
if(v.isVideo())
{
}
}
return total;
}
I'm not sure how to get 'runtime' which is a variable from the video class, do I have to loop differently? 我不确定如何获取“运行时”,它是视频类中的变量,我是否必须以不同的方式循环? I am not sure how I can get variables from child classes, I assume its possible(I hope!)
我不确定如何从子类中获取变量,我认为它是可能的(我希望!)
You have to use instanceof
and cast it to the correct class. 您必须使用
instanceof
并将其强制转换为正确的类。
eg 例如
if(v instanceof Video){
Video a = (Video) v;
a.childMethodOfVideo();
}
if(v instanceof Audio){
Audio a = (Audio) v;
a.childMethodOfAudio();
}
Not completely sure what you are trying to achieve, but if you want the variables a certain class has, you can use reflection API for it: 不确定要实现的目标,但是如果您希望某个类具有变量 ,则可以使用反射API :
Field[] fields = v.getClass().getFields();
for (Field f : fields) System.out.println(f.getName());
Similarly if you want the methods: 同样,如果您需要方法:
Method[] methods = v.getClass().getMethods()();
for (Method m : methods) m.invoke(arguments...);
I must warn you that using reflection has a lot of cons (performance, safety) - and many times if you need to use it, it indicates a code smell . 我必须警告您,使用反射有很多弊端(性能,安全性)-如果需要使用反射,则很多次它表明代码有异味 。
If you are trying to do some specific behavior for a certain class, the correct way to do it is implement it as abstract method, and call it - the dynamic type will be chosen, and the desired method will be called: 如果您尝试对某个类进行某些特定的操作,则正确的方法是将其实现为抽象方法,然后调用它-将选择动态类型,然后将调用所需的方法:
public abstract static class Media {
abstract public void foo();
}
public static class Video extends Media{
@Override
public void foo() {
System.out.println("video");
}
}
public static class Image extends Media{
@Override
public void foo() {
System.out.println("image");
}
}
public static void main(String ar[]) {
Media m = new Video();
m.foo();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.