Created
April 25, 2016 16:09
-
-
Save Frisch12/9e335d2caf9d2e30cf1a7f13819091a6 to your computer and use it in GitHub Desktop.
Reflection util for IntelliJ plugins to reflect over project libraries
This file contains 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 com.intellij.openapi.project.Project; | |
import com.intellij.openapi.roots.libraries.LibraryUtil; | |
import com.intellij.util.containers.WeakHashMap; | |
import java.lang.annotation.Annotation; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.net.URLClassLoader; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Set; | |
import java.util.stream.Collectors; | |
import java.util.stream.StreamSupport; | |
public class LibraryReflectionUtil { | |
private static WeakHashMap<Project, LibraryReflectionUtil> projectIntances = new WeakHashMap<>(); | |
private ClassLoader loader; | |
private Reflections reflections; | |
public static void initForProject(Project project) { | |
LibraryReflectionUtil result = projectIntances.get(project); | |
if(result == null) { | |
List<URL> collect = StreamSupport.stream(Arrays.spliterator(LibraryUtil.getLibraryRoots(project)), false).map(f -> { | |
try { | |
if(f.getCanonicalPath() != null) | |
return new URL(f.getCanonicalPath()); | |
} catch (MalformedURLException ignored) { | |
} | |
return null; | |
}).filter(f -> f != null).collect(Collectors.toList()); | |
ClassLoader loader = URLClassLoader.newInstance( | |
(URL[]) collect.toArray(), | |
LibraryReflectionUtil.class.getClassLoader()); | |
LibraryReflectionUtil reflectionUtil = new LibraryReflectionUtil(); | |
reflectionUtil.loader = loader; | |
reflectionUtil.init(); | |
projectIntances.put(project, reflectionUtil); | |
} | |
} | |
private LibraryReflectionUtil() { } | |
public static LibraryReflectionUtil getInstance(Project project) { | |
return projectIntances.get(project); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment