Finding and Creating Instance of Every Class in Package
I've been trying to understand how one would go about generically creating an object of every single class in a package.
After some searching I found this code posted on the internet:
Code:
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes.toArray(new Class[classes.size()]);
}
Code:
private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException
{
List<Class> classes = new ArrayList<Class>();
if (!directory.exists())
{
return classes;
}
File[] files = directory.listFiles();
for (File file : files)
{
if (file.isDirectory())
{
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
}
else if (file.getName().endsWith(".class"))
{
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
It seemed pretty promising, but after continuous attempts to achieve my goal, I ultimately found no solution.
Code:
Class[] classes = getClasses("com.gmail.jtripled.Test.Listeners");
for(Class cl : classes)
{
Constructor con = cl.getConstructor(Test.class);
Object newInstance = con.newInstance(this);
}
This snippet of code was what I had come up with, but never actually worked. I haven't found a single thing on the internet that would make me believe this is possible as it seems you still have to know the class of the object when you declare it -- and that just sounds like a really complicated way to declare an object.
Inside the package are the classes:
com.gmail.jtripled.Test.Listeners.PlayerListener.c lass
com.gmail.jtripled.Test.Listeners.EntityListener.c lass
They are for the game Minecraft where I'm trying to develop a plugin -- not that that's really important, but just mentioning that they don't have some main function or anything. That previously posted attempt at instantiating each of the classes does take place in the method called on the enabling of said plugin.
Sorry if I'm not clear enough, my Java vocabulary isn't the best, and if you need more explanation or code to look at I'd be glad to post it!