![](/img/trans.png)
[英]How to check if the “?” of a Class<?> object instanceof SomeInterface
[英]check if an item in an array list is an instanceof an object created in another class
我正在使用一个foreach循环来遍历在同一父类的不同子类中创建的对象的数组列表,然后,如果使用instanceof布尔表达式的语句检查每个循环现在所处的特定项属于哪个子类,但是我认为我没有使用正确实例的布尔表达式,因为在调试我的代码时,所有的if语句都会被跳过。
for (Appointment item: AppointmentBook.apps){
if (item instanceof Onetime){
boolean checkOnce = ((Onetime) item).occursOn(month, day, year);
if (checkOnce == true){
appointmentsToday++;
appsToday.add(item);
}//check once true
else appointmentsToday = 0;
}//if onetime
约会是Onetime的超类。 AppointmentBook预约数组列表所在的类。 appearOn是Onetime类中的方法
您应该始终避免这样的代码:
if (item instanceof TypeA) {
...
} else
if (item instanceof TypeB) {
...
} else ...
使用多态性,否则您将遭受高耦合 。
您使用” nstanceof`”的布尔表达式是正确的。 我怀疑您用来填充AppointmentBook类的apps静态字段的方法是问题的根源。 如果调试显示每个if语句都被跳过,那是唯一的逻辑解释。 我尝试重现一些与您的代码相似的代码以对其进行测试,并且它工作正常。
这是我所做的
首先是预约课程:
public class Appointment {
}
第二个AppointmentBook类
import java.util.ArrayList;
import java.util.List;
public class AppointmentBook {
public static List<Appointment> apps = new ArrayList<Appointment>();
public AppointmentBook addAppointment(Appointment app) {
apps.add(app);
return this;
}
}
第三是扩展约会的OneTime类(因为您说约会是OneTime的超类)
public class OneTime extends Appointment {
public boolean occursOn(int month, int day, int year) {
if (day >= 15) {
return true;
} else {
return false;
}
}
}
如您所见,我正在使用一个琐碎的测试用例,以从thensOn方法返回布尔结果(仅出于测试目的)
然后,我创建了以下测试类。 我用四个约会实例填充AppointmentBook应用程序,其中两个是“ instanceof ” OneTime
public class AppointmentTest {
static int year = 2015;
static int month = 3;
static int day = 15;
public static void main(String[] args) {
AppointmentBook book = new AppointmentBook();
book.addAppointment(new Appointment())
.addAppointment(new OneTime())
.addAppointment(new Appointment())
.addAppointment(new OneTime());
for (Appointment item: AppointmentBook.apps) {
if (item instanceof OneTime) {
boolean checkOnce = ((OneTime)item).occursOn(month, day, year);
if (checkOnce == true) {
System.out.println("We have a checked OneTime instance...");
} else {
System.out.println("We have an unchecked OneTime instance...");
}
} else {
System.out.println("Not a OneTime instance...");
}
}
}
}
下图显示了获得的结果:它证明您的instanceof表达式正确,并且问题很可能与填充apps字段的方法有关
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.