zoukankan      html  css  js  c++  java
  • java打印出继承体系的类(包括抽象类)、接口、域字段

    搜索了很多文章都说需要newInstance进行实例化,但抽象的类进行实例化肯定是有问题的
    所以这里的实现相对更好。如有问题欢迎大家留言指正

    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
    

    其中用到的工具类

    public class P {
    
        public static void print(Object s) {
            System.out.print(s);
        }
    
        public static void println(Object s) {
            System.out.println(s);
        }
    }
    
  • 相关阅读:
    转换流与标准的输入输出流
    缓冲流
    节点流(文件流) FileInputStream & FileOutputStream & FileReader & FileWriter
    IO流概述
    File类的使用
    枚举&注解
    泛型的使用
    Collections工具类
    Map接口之HashMap,LinkedHashMap,TreeMap
    MySQL 高可用之MHA
  • 原文地址:https://www.cnblogs.com/so-easy/p/11521637.html
Copyright © 2011-2022 走看看