1) You need to find all the available subclasses of class A. To do this, you need to scan all the classes in the Java classpath. To keep things simple, we can assume that all subclasses are in the same place as A.class. It is assumed that A is in the bank or in the folder. We can find out its actual location as
URL url = A.class.getProtectionDomain().getCodeSource().getLocation();
2) Suppose this is a folder, for example, the file: / D: / workspace1 / x / target / classes /. Now we have to go through all the .class files in this folder and subfolders. For this we can use File.listFiles or Java 7 NIO2. We have 2 options
a) load each class and check its superclass
Class cls = Class.forName(); if (cls.getSuperClass() == A.class) { ...
b) use the javaassist framework http://www.javassist.org or similarly work with the class file directly
DataInputStream ds = new DataInputStream(new BufferedInputStream(path)); ClassFile cf = new ClassFile(ds); String superClass = cf.getSuperClass(); if (superClass.equals("A")) { Class cls = Class.forName(cf.getName()); ...
option b only loads the classes that you really need, option a is simpler, but it loads all the classes in a folder
In both cases, you create an instance as
A a = (A) cls.newInstance();
assuming all subclasses have a no-arg constructor
source share