Java instanceof 与isAssignableFrom
代码如下:
先定义一个接口:
public interface InstanceTest {
public String getString();
}
实现类A:
public class InstanceA implements InstanceTest {
@Override
public String getString() {
return "This is implements A.";
}
}
实现类B:
public class InstanceB implements InstanceTest {
@Override
public String getString() {
return "This is implements B.";
}
}
测试类:
/**
*
* @author David John
*
* instanceof 针对实例 ; isAssignableFrom 针对class对象
* isAssignableFrom 是用来判断一个类Class1和另一个类Class2是否相同或是另一个类的超类或接口
* 而 instanceof 是用来判断一个对象实例是否是一个类或接口的或其子类子接口的实例。
* 其中instanceof是子-->父
* isAssignableFrom是父-->子
* 我们应该尽量少用instanceof 运算符,应该尽量用多态来替代它
*/
public class InstAndIAF {
public static void action(InstanceTest test){
if(test instanceof InstanceA){
System.out.println("Act like InstanceA...");
}
if(test instanceof InstanceB){
System.out.println("Act like InstanceB...");
}
}
public static void action(InstanceA ia){
System.out.println("Use polymorphic, Act like InstanceA...");
}
public static void action(InstanceB ib){
System.out.println("Use polymorphic, Act like InstanceB...");
}
public static void judgeAction(InstanceTest test){
if(test instanceof InstanceA){
InstAndIAF.action((InstanceA)test);
}
if(test instanceof InstanceB){
InstAndIAF.action((InstanceB)test);
}
}
public static void main(String[] args) {
InstanceTest test1 = new InstanceA();
InstanceTest test2 = new InstanceB();
System.out.println(test1 instanceof InstanceTest);
System.out.println(test2 instanceof InstanceTest);
System.out.println(InstanceTest.class.isAssignableFrom(InstanceA.class));
System.out.println(InstanceTest.class.isAssignableFrom(InstanceB.class));
List<String> list = new ArrayList<String>();
System.out.println(list instanceof ArrayList);
System.out.println(list.getClass().isAssignableFrom(List.class));
System.out.println(List.class.isAssignableFrom(list.getClass()));
InstAndIAF.action(test1);
InstAndIAF.action(test2);
InstAndIAF.judgeAction(test2);
}
}
运行结果:
true
true
true
true
true
false
true
Act like InstanceA...
Act like InstanceB...
Use polymorphic, Act like InstanceB...
That'all...