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);
}
}