Skip to content

Instantly share code, notes, and snippets.

@joubin
Last active March 4, 2016 04:27
Show Gist options
  • Save joubin/fd2f9bb3e6503f0e2903 to your computer and use it in GitHub Desktop.
Save joubin/fd2f9bb3e6503f0e2903 to your computer and use it in GitHub Desktop.
A means of getting all subclasses of a class
/**
* Assume class A; class B extends A; class C extends B;
*/
public static void main(String[] args) throws ClassNotFoundException {
A obj = new C();
System.out.println(obj.getClass());
Class.forName(String.valueOf(obj.getClass().getName()));
System.out.println(GetClassesType(obj.getClass()));
}
public static List<Type> GetClassesType(Class cls) throws ClassNotFoundException {
List<Type> clsList = new ArrayList<>();
clsList.add(cls);
Type name;
while ((name = cls.getGenericSuperclass()) != java.lang.Object.class){
clsList.add(name);
cls = Class.forName(name.getTypeName());
}
return clsList;
}
public static List<String> GetClassesString(Class cls) throws ClassNotFoundException{
List<String> strs = new ArrayList<>();
GetClassesType(cls).forEach(item -> strs.add(item.getTypeName()));
return strs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment