Created
April 21, 2023 09:40
-
-
Save betterclient/325300e8a9a6b9a51b5eca764b090183 to your computer and use it in GitHub Desktop.
Reflection Utility (Uses ASM)
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
import org.objectweb.asm.ClassReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.net.URLClassLoader; | |
import java.util.ArrayList; | |
import java.util.Enumeration; | |
import java.util.List; | |
import java.util.jar.JarEntry; | |
import java.util.jar.JarFile; | |
public class Reflect { | |
private static URL[] urls; | |
private static File[] files; | |
public final Class<?> superClass; | |
public Reflect(Class<?> superClass) throws MalformedURLException { | |
this.superClass = superClass; | |
if(this.getClass().getClassLoader() instanceof URLClassLoader loader) { | |
Reflect.urls = loader.getURLs(); //Quixotic Check | |
} else { | |
String cp = System.getProperty("java.class.path"); | |
String[] elements = cp.split(File.pathSeparator); | |
if (elements.length == 0) { | |
throw new RuntimeException("ClassPath is empty."); | |
} | |
int index = 0; | |
URL[] findUrls = new URL[elements.length]; | |
File[] findFiles = new File[elements.length]; | |
for (String el : elements) { | |
File file = new File(el); | |
URL url = file.toURI().toURL(); | |
findFiles[index] = file; | |
findUrls[index] = url; | |
index++; | |
} | |
Reflect.urls = findUrls; | |
} | |
} | |
public List<Class<?>> getAll(ClassLoader loadWith) throws IOException, ClassNotFoundException { | |
List<Class<?>> found = new ArrayList<>(); | |
for (File f : Reflect.files) { | |
JarFile file = new JarFile(f); | |
Enumeration<JarEntry> entries = file.entries(); | |
while(entries.hasMoreElements()) { | |
JarEntry current = entries.nextElement(); | |
if(!current.getName().endsWith(".class")) continue; | |
InputStream is = file.getInputStream(current); | |
ClassReader reader = new ClassReader(is.readAllBytes()); | |
if(reader.getSuperName().equals(this.superClass.getName())) { | |
found.add(loadWith.loadClass(reader.getClassName())); | |
} | |
is.close(); | |
} | |
file.close(); | |
} | |
return found; | |
} | |
public List<Class<?>> getAll() throws IOException, ClassNotFoundException { | |
return this.getAll(this.getClass().getClassLoader()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment