Write a program design document-or rather, I had the opportunity to create a program design document from the source code, but the design document says, "Write all the parent class names and all the interfaces implemented in the created Java class together. It was something like. It's a hassle to make this foolishly by hand. So I decided to write a program called __ "Recursely find the parent class and interface from the class name" __. Below is a sample of it.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
//Create a class object from the class name.
Class<?> pivotClass = Class.forName("java.util.ArrayList");
//Follow the superclass recursively.
List<Class<?>> classes = new ArrayList<>();
Class<?> superClass = pivotClass;
while (superClass != null) {
classes.add(superClass);
superClass = superClass.getSuperclass();
}
//Get a list of recursively acquired superclasses.
for (Class<?> clazz : classes) {
System.out.println(clazz.getName());
}
/* java.util.ArrayList
java.util.AbstractList
java.util.AbstractCollection
java.lang.Object */
//Get a list of implemented interfaces&Output.
Class<?>[] interfaces = pivotClass.getInterfaces();
for (Class<?> interfaze : interfaces) {
System.out.println(interfaze.getName());
}
/* java.util.List
java.util.RandomAccess
java.lang.Cloneable
java.io.Serializable */
}
}
It's a little strange that the class itself can be treated as a class, but it's useful once you get used to it. Hurray for metaprogramming (´ ・ ω ・ `)
Recommended Posts