java.lang.Class类的isInstance()方法用于检查指定的对象是否兼容分配给该Class的实例。如果指定对象为非null,并且可以强制转换为此类的实例,则该方法返回true。否则返回false。
用法:
public boolean isInstance(Object object)
参数:此方法接受object作为参数,这是要检查与此Class实例的兼容性的指定对象。
返回值:如果指定对象为非null,并且可以强制转换为此类的实例,则此方法返回true。否则返回false。
下面的程序演示了isInstance()方法。
示例1:
// Java program to demonstrate isInstance() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// get the Class instance using forName() method
Class c = Class.forName("java.lang.String");
System.out.println("Class represented by c: "
+ c.toString());
// Check if object c is compatible
// using isInstance() method
System.out.println("Is c compatible: "
+ myClass.isInstance(c));
}
}
输出:
Class represented by myClass: class Test Class represented by c: class java.lang.String Is c compatible: false
示例2:
// Java program to demonstrate isInstance() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// get the Class instance using forName() method
Class c = Class.forName("Test");
System.out.println("Class represented by c: "
+ c.toString());
// Check if object c is compatible
// using isInstance() method
System.out.println("Is c compatible: "
+ myClass.isInstance(c));
}
}
输出:
Class represented by myClass: class Test Class represented by c: class Test Is c compatible: false
参考: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isInstance-java.lang.Object-
相关用法
- Java Class desiredAssertionStatus()用法及代码示例
- Java Class getProtectionDomain()用法及代码示例
- Java Class getResource()用法及代码示例
- Java Class getResourceAsStream()用法及代码示例
- Java Class getClassLoader()用法及代码示例
- Java Class getGenericSuperclass()用法及代码示例
- Java Class getCanonicalName()用法及代码示例
- Java Class getEnumConstants()用法及代码示例
- Java Class getDeclaredMethod()用法及代码示例
- Java Class getDeclaredField()用法及代码示例
- Java Class getDeclaredConstructor()用法及代码示例
- Java Class getConstructor()用法及代码示例
- Java Class getMethod()用法及代码示例
- Java Class getField()用法及代码示例
注:本文由纯净天空筛选整理自srinam大神的英文原创作品 Class isInstance() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。