我们总是喜欢崇敬我们的人,但并不永远喜欢我们所崇敬的人。——拉罗什富科

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package io.github.vampireachao.stream.core.clazz;

import io.github.vampireachao.stream.core.lambda.function.SerFunc;
import io.github.vampireachao.stream.core.lambda.function.SerSupp;
import io.github.vampireachao.stream.core.reflect.ReflectHelper;
import io.github.vampireachao.stream.core.stream.Steam;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
* ClassHelper
*
* @author VampireAchao
* @since 2023/1/9
*/
public class ClassHelper {

private ClassHelper() {
/* Do not new me! */
}

public static List<Class<?>> scanClasses(String packageName) {
Enumeration<URL> resources = ((SerSupp<Enumeration<URL>>) () ->
ClassLoader.getSystemClassLoader().getResources(packageName.replace(".", "/"))
).get();
return Steam.of(Collections.list(resources))
.map(URL::getFile)
.map((SerFunc<String, File>) f -> new File(URLDecoder.decode(f, StandardCharsets.UTF_8.name())))
.filter(dir -> dir.exists() && dir.isDirectory())
.map(File::listFiles)
.flat(files -> Steam.of(files).map(File::getAbsolutePath)
.filter(path -> path.endsWith(".class"))
.map(path -> path.substring(path.lastIndexOf("\\") + 1, path.length() - 6))
.<Class<?>>map(className -> ReflectHelper.loadClass(packageName + "." + className)))
.toList();
}

}

使用:

1
2
List<Class<?>> classes = ClassHelper.scanClasses(ClassHelper.class.getPackage().getName());
Assertions.assertTrue(classes.stream().anyMatch(clazz -> clazz.getName().equals(ClassHelper.class.getName())));