Java class inherits print out system (including abstract classes), interfaces, domain field

Search a lot of articles saying newInstance need to be instantiated, but the abstract class is instantiated there is definitely a problem
it is relatively better achieved here. If you have questions welcome to correct me a message

import java.lang.reflect.Field;

public class Shapes {

    static void printClassTree(Class<?> o) {
        //基类Object
        if (o == Object.class) {
            P.println("Object");
            return;
        }
        printClassTree(o.getSuperclass());
        //继承的类
        P.print(o.getSimpleName());
        //实现的接口
        if (o.getInterfaces().length > 0) P.print("实现的接口: ");
        for (Class face : o.getInterfaces()) {
            P.print(face.getSimpleName() + " ");
        }
        //域
        if (o.getDeclaredFields().length > 0) P.print("定义的域:");
        for (Field field : o.getDeclaredFields()) {
            P.print(field.getName() + " ");
        }
        P.println();
    }

    public static void main(String[] args) {

        printClassTree(Rhomboid.class);

    }
}

interface Color {
    void paint();
}

abstract class Shape implements Color {
    static String signClass;

    void draw() {
        P.println(this + ".draw()");
    }

    void rotate() {
        if (this instanceof Circle) {
            return;
        }
        P.println(this.getClass());
    }

    public void paint() {}

    abstract public String toString();
}

class Rhomboid extends Shape {

    public String toString() {
        return "Rhomboi";
    }
}
//结果
Object
Shape实现的接口: Color 定义的域:signClass 
Rhomboid

Guess you like

Origin www.cnblogs.com/so-easy/p/11521637.html