Last active
March 4, 2016 04:27
-
-
Save joubin/fd2f9bb3e6503f0e2903 to your computer and use it in GitHub Desktop.
A means of getting all subclasses of a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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