LibsDisguises/src/me/libraryaddict/disguise/utilities/ClassGetter.java

90 lines
2.7 KiB
Java
Raw Normal View History

2014-05-22 23:13:35 +02:00
package me.libraryaddict.disguise.utilities;
import java.net.URL;
import java.net.URLDecoder;
2014-05-22 23:13:35 +02:00
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
2016-05-09 17:28:38 +02:00
import org.bukkit.entity.Entity;
2014-05-22 23:13:35 +02:00
/**
* User: Austin Date: 4/22/13 Time: 11:47 PM (c) lazertester
*/
// Code for this taken and slightly modified from
// https://github.com/ddopson/java-class-enumerator
2016-05-09 17:28:38 +02:00
public class ClassGetter
{
2014-05-22 23:13:35 +02:00
2016-05-09 17:28:38 +02:00
public static ArrayList<Class<?>> getClassesForPackage(String pkgname)
{
ArrayList<Class<?>> classes = new ArrayList<>();
2014-05-22 23:13:35 +02:00
// String relPath = pkgname.replace('.', '/');
// Get a File object for the package
CodeSource src = Entity.class.getProtectionDomain().getCodeSource();
2016-05-09 17:28:38 +02:00
if (src != null)
{
2014-05-22 23:13:35 +02:00
URL resource = src.getLocation();
resource.getPath();
processJarfile(resource, pkgname, classes);
}
2016-05-09 17:28:38 +02:00
2014-05-22 23:13:35 +02:00
return classes;
}
2016-05-09 17:28:38 +02:00
private static Class<?> loadClass(String className)
{
try
{
2014-05-22 23:13:35 +02:00
return Class.forName(className);
2016-05-09 17:28:38 +02:00
}
catch (ClassNotFoundException e)
{
2014-05-22 23:13:35 +02:00
throw new RuntimeException("Unexpected ClassNotFoundException loading class '" + className + "'");
2016-05-09 17:28:38 +02:00
}
catch (NoClassDefFoundError e)
{
2014-05-22 23:13:35 +02:00
return null;
}
}
2016-05-09 17:28:38 +02:00
private static void processJarfile(URL resource, String pkgname, ArrayList<Class<?>> classes)
{
try
{
String relPath = pkgname.replace('.', '/');
String resPath = URLDecoder.decode(resource.getPath(), "UTF-8");
String jarPath = resPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
2014-05-25 07:58:53 +02:00
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
2016-05-09 17:28:38 +02:00
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
String className = null;
if (entryName.endsWith(".class") && entryName.startsWith(relPath)
2016-05-09 17:28:38 +02:00
&& entryName.length() > (relPath.length() + "/".length()))
{
className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
}
2016-05-09 17:28:38 +02:00
if (className != null)
{
Class<?> c = loadClass(className);
2016-05-09 17:28:38 +02:00
if (c != null)
{
classes.add(c);
}
}
2014-05-22 23:13:35 +02:00
}
2016-05-09 17:28:38 +02:00
}
catch (Exception ex)
{
ex.printStackTrace(System.out);
2014-05-22 23:13:35 +02:00
}
}
}