Tuesday, September 16, 2014

Example of getSimpleName()

The getSimpleName() method returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

This example modify from last post to list superclasses with simple name.


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();
            if(someClass!=null){
                info.append("superClass: ").append(someClass.getSimpleName()).append("\n");
            }else{
                info.append("superClass: ").append("null").append("\n");
            }
            
        }while(someClass != null);
        
        info.append("=====").append("\n");
        System.out.println(info);
    }

}

class SubJavaGetSuperClass extends JavaGetSuperClass{
        
}

No comments:

Post a Comment