Tuesday, September 16, 2014

Example of using getSuperclass()

The getSuperclass() method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.

This example list the superclasses of a class.


package javagetsuperclass;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaGetSuperClass {

    public static void main(String[] args) {

        JavaGetSuperClass me = new JavaGetSuperClass();
        me.doSomething();
        
        SubJavaGetSuperClass subMe = new SubJavaGetSuperClass();
        subMe.doSomething();
        
        Class testClass = javafx.scene.chart.AreaChart.class;
        printClassInfo(testClass);
    }

    public void doSomething(){
        printClassInfo(this.getClass());
    }
    
    static private void printClassInfo(Class someClass){

        StringBuilder info = new StringBuilder();
        
        info.append("someClass: ").append(someClass).append("\n");
        
        do{
            someClass = someClass.getSuperclass();
            info.append("superClass: ").append(someClass).append("\n");
        }while(someClass != null);
        
        info.append("=====").append("\n");
        System.out.println(info);
    }

}

class SubJavaGetSuperClass extends JavaGetSuperClass{
        
}

No comments:

Post a Comment