Created
February 19, 2020 12:56
-
-
Save kazuhito-m/0170581800f53a91b8790b5611a1c995 to your computer and use it in GitHub Desktop.
パッケージからクラスの一覧を取得するやつ
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 java.io.IOException; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.List; | |
import static java.util.stream.Collectors.toList; | |
public class ClassesListUper { | |
public List<Class<?>> classesOf(Package targetPackage) throws IOException, URISyntaxException { | |
ClassLoader classLoader = Thread.currentThread() | |
.getContextClassLoader(); | |
String packageDirectories = targetPackage.getName() | |
.replace(".", "/"); | |
URI uri = classLoader.getResource(packageDirectories) | |
.toURI(); | |
Path folder = Paths.get(uri); | |
return Files.list(folder) | |
.map(Path::getFileName) | |
.map(this::toClassName) | |
.map(name -> toClass(name, targetPackage)) | |
.collect(toList()); | |
} | |
private String toClassName(Path filePath) { | |
String name = filePath.getFileName().toString(); | |
return name.substring(0, name.lastIndexOf('.')); | |
} | |
private Class<?> toClass(String className, Package targetPackage) { | |
try { | |
String fqcn = targetPackage.getName() + "." + className; | |
return Class.forName(fqcn); | |
} catch (ClassNotFoundException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment