Close

Java Reflection - Class.isInstance() Examples

Code Snippets Java Reflection Java 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public boolean isInstance(Object obj)
Parameters:
obj - the object to check
Returns:
true if obj is an instance of this class

Examples


package com.logicbig.example.clazz;

public class IsInstanceExample {

public static void main(String... args) {
Object object = new Thread();
boolean b = Runnable.class.isInstance(object);
System.out.println(b);
b = Thread.class.isInstance(object);
System.out.println(b);
}
}

Output

true
true




package com.logicbig.example.clazz;

public class IsInstanceExample2 {

public static void main(String... args) throws IllegalAccessException, InstantiationException {
int i = 5;
boolean b = Object.class.isInstance(i);
System.out.println(b);
}
}

Output

true




JLabel extends Component

package com.logicbig.example.clazz;

import javax.swing.*;
import java.awt.*;

public class IsInstanceExample3 {

public static void main(String... args) {
Object object = new JLabel();
boolean b = Component.class.isInstance(object);
System.out.println(b);
}
}

Output

true




package com.logicbig.example.clazz;

public class IsInstanceExample4 {

public static void main(String... args) {
Object object = null;
boolean b = void.class.isInstance(object);
System.out.println(b);

b = Void.class.isInstance(object);
System.out.println(b);
}
}

Output

false
false

Arrays:

package com.logicbig.example.clazz;

public class IsInstanceExample5 {

public static void main(String... args) {
System.out.println("-- primitive arrays --");
int[] numbers = {1, 2};
boolean b = Object.class.isInstance(numbers);
System.out.println(b);

b = Object[].class.isInstance(numbers);
System.out.println(b);

System.out.println("-- object arrays --");
Integer[] numbers2 = {1, 2};
b = Object.class.isInstance(numbers2);
System.out.println(b);

b = Object[].class.isInstance(numbers2);
System.out.println(b);

b = Number[].class.isInstance(numbers2);
System.out.println(b);

}
}

Output

-- primitive arrays --
true
false
-- object arrays --
true
true
true




See Also