如何将instanceof
缩小到特定的孩子,而不必与父类结束。
例如,如果我应该有一个父类StackoverflowUsers
,那么我有TenKUsers
的直接子类,HundredKusers
等等。现在我的问题是如何使用{{1}如果instanceof
是Object
的直接子类之一的实例,而不是最终选择StackoverflowUsers
是object
的实例。那可能吗?
答案 0 :(得分:4)
只需使用instanceof TenKUsers
(等)成语。
它会告诉您正在查看的对象是否是该基类的子对象。
由于您暗示TenKUsers
是StackoverflowUsers
的孩子,当然,instanceof StackoverflowUsers
对该对象来说是<{1}}。
答案 1 :(得分:2)
您可以通过选中.getClass()
排除超类本身,但是&#34;孙子&#34;也将匹配...
你可以使用反射,但一般情况下应该避免反思(有点&#34;作弊&#34;)。
public class T {
static class StackoverflowUsers {}
static class TenKUsers extends StackoverflowUsers {}
static class HundredKusers extends StackoverflowUsers {}
static class EtcEtc extends TenKUsers {}
public static void main(String[] args) {
System.out.println("Instance of String: "+checkInstance(new String()));
System.out.println("Instance of StackoverflowUsers (superclass): "+checkInstance(new StackoverflowUsers()));
System.out.println("Instance of TenKUsers (direct subclass): "+checkInstance(new TenKUsers()));
System.out.println("Instance of HundredKusers (direct subclass): "+checkInstance(new HundredKusers()));
System.out.println("Instance of EtcEtc (indirect subclass): "+checkInstance(new EtcEtc()));
System.out.println();
System.out.println("using reflection:");
System.out.println("Instance of String: "+checkInstanceUsingReflection(new String()));
System.out.println("Instance of StackoverflowUsers (superclass): "+checkInstanceUsingReflection(new StackoverflowUsers()));
System.out.println("Instance of TenKUsers (direct subclass): "+checkInstanceUsingReflection(new TenKUsers()));
System.out.println("Instance of HundredKusers (direct subclass): "+checkInstanceUsingReflection(new HundredKusers()));
System.out.println("Instance of EtcEtc (indirect subclass): "+checkInstanceUsingReflection(new EtcEtc()));
}
private static boolean checkInstance(Object o) {
return (o instanceof StackoverflowUsers) && (o.getClass() != StackoverflowUsers.class);
}
private static boolean checkInstanceUsingReflection(Object o) {
Class<?> superclass = o.getClass().getSuperclass();
return superclass == StackoverflowUsers.class;
}
}
返回:
Instance of String: false
Instance of StackoverflowUsers (superclass): false
Instance of TenKUsers (direct subclass): true
Instance of HundredKusers (direct subclass): true
Instance of EtcEtc (indirect subclass): true
using reflection:
Instance of String: false
Instance of StackoverflowUsers (superclass): false
Instance of TenKUsers (direct subclass): true
Instance of HundredKusers (direct subclass): true
Instance of EtcEtc (indirect subclass): false
也许你应该重新考虑你的课程。似乎TenKUsers
也可以是存储在StackoverflowUsers中的布尔标志。甚至更好:给你的StackoverflowUsers EnumSet<Archievments>
并让Archievments包含&#34; TenKUser&#34;和&#34; HundredKusers&#34;。
答案 2 :(得分:0)
除了Mena的答案之外,如果你想使用instanceof
来检查,你可以使你的超类Stackoverflowusers
抽象,以确保不存在任何实例,然后检查:
object instanceof Stackoverflowusers