Many developers use class.isInstance() to know the parameter’s Type. It’s fine if your parameter is object reference type.
Unfortunately, sometimes the parameter includes primitive types, and it will give you unexpected answer. The correct way to know your parameter type should be class.isAssignableFrom().


import java.lang.*;
import java.util.*;

public class TestClassType
{
	public static void main(String[] args) throws Exception
	{
		char x = 'a';
		int y = 6;
		String z = "I am Loving";

		//use instanceof
		System.out.println("Test case: instanceof");
		/** Syntax error. Can't be compiled!!	The instanceof operator can only be used with object reference types, not primitive types.
		if (x instanceof char) System.out.println("x is char!");
		if (y instanceof int) System.out.println("y is int!");
		*/
		if (z instanceof String) System.out.println("z is String!");
		System.out.print("\n");

		//use isInstance
		System.out.println("Test case: isInstance");
		/** The class.isInstance() only supports object reference types as parameter not primitive types.*/
		if (char.class.isInstance(x)) System.out.println("x is char!"); //false
		if (int.class.isInstance(y)) System.out.println("y is int!");	//false
		if (String.class.isInstance(z)) System.out.println("z is String!");
		System.out.print("\n");

		//use isAssignableFrom
		System.out.println("Test case: isAssignableFrom");
		/** Assume we use java reflection to get the paramter type. i.e. Field.getType()*/
		Class typeX = char.class; 	//field x type
		Class typeY = int.class;	//field y type
		Class typeZ = String.class; //field z type

		if (char.class.isAssignableFrom(typeX)) System.out.println("x is char!");
		if (int.class.isAssignableFrom(typeY)) System.out.println("y is int!");
		if (String.class.isAssignableFrom(typeZ)) System.out.println("z is String!");

	}

}

Reference:
isAssignableFrom/isInstance redundant ?

Java Snippets: Class.isAssignableFrom() vs. instanceof

Advertisements