Thursday, October 6, 2011

Java - getting type of Object

You can use getClass() to get the java.lang.Class object that represents the type of the object.
view plaincopy to clipboardprint?

    public void myMethod(Object obj) {  
        Class cls = obj.getClass();  
        System.out.println("The type of the object is: " + cls.getName());  
    } 


If you just want to know if an object is an instance of or extends a certain class, or implements a certain interface, you can use the instanceof keyword.
view plaincopy to clipboardprint?

    public void myMethod(Object obj) {  
        if (obj instanceof String) {  
            System.out.println("It's a String");  
        }  
        else {  
            System.out.println("It's not a String");  
        }  
    }   

Code Example

class A
{
    void Afoo()
    {
       
        System.out.println("I am from Afoo ");
    }

}


class B extends A
{
    void Bfoo()
    {
       
        System.out.println("I am from Bfoo ");
    }

}



public class TypeofExampleClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        B oB = new B();
       
        Class cls = oB.getClass();  

        System.out.println("cls.getName() = " + cls.getName());
       
       
       
        String x="hello";       
        cls = x.getClass();
        System.out.println("cls.getName() = " + cls.getName());
       
       
         if (x instanceof String) {  
                System.out.println("x is a String");  
            }  
            else {  
                System.out.println("x is not a String");  
            }  


         if (oB instanceof B) {  
                System.out.println("oB is a B");  
            }  
            else {  
                System.out.println("oB is not a B");  
            }
       
         if (oB instanceof A) {  
                System.out.println("oB is a A");  
            }  
            else {  
                System.out.println("oB is not a A");  
            }
       

    }

}

No comments:

Post a Comment

Blog Archive