编写代码经常需要判断类型,用于执行不同的事件,以下整理了几种方法
代码语言:java复制package other;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class JudgeClass {
public class F
{
}
public class S extends F
{
}
/// 通过 instanceof
@Test
public void judge1Test() {
/// 此方法不能判断父子类问题
F f1 = new F();
F s1 = new S();
assertEquals(true, f1 instanceof F); /// true
assertEquals(true, s1 instanceof S); /// true
assertEquals(true, s1 instanceof F); /// true
assertEquals(true, f1 instanceof S); /// false
}
/// instanceof 的另外一种写法
@Test
public void judge2Test() {
/// 方法同上
F f1 = new F();
F s1 = new S();
assertEquals(true, f1.getClass().isInstance(f1)); /// true
assertEquals(true, s1.getClass().isInstance(s1)); /// true
assertEquals(true, f1.getClass().isInstance(s1)); /// true
assertEquals(true, s1.getClass().isInstance(f1)); /// false
}
/// 通过isAssignableFrom,可以处理父子关系
@Test
public void judge3Test() {
F f1 = new F();
F s1 = new S();
assertEquals(true, f1.getClass().isAssignableFrom(F.class)); /// true
assertEquals(true, s1.getClass().isAssignableFrom(S.class)); /// true
assertEquals(true, f1.getClass().isAssignableFrom(S.class)); /// true
assertEquals(true, s1.getClass().isAssignableFrom(F.class)); /// false
}
/// 通过类名称(不推荐)
@Test
public void judge4Test() {
F f1 = new F();
F s1 = new S();
assertEquals("other.JudgeClass$F", f1.getClass().getName()); /// true
assertEquals("other.JudgeClass$S", s1.getClass().getName()); /// true
}
/// 直接比较class,毕竟class也是对象
@Test
public void judge5Test() {
F f1 = new F();
F s1 = new S();
assertEquals(true, f1.getClass().equals(F.class)); /// true
assertEquals(F.class, f1.getClass()); /// true
assertEquals(S.class, s1.getClass()); /// true
assertEquals(F.class, s1.getClass()); /// false
}
}