原理:
1、扫描指定路劲下的JAVA文件
2、利用反射
package com.util;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
/**
* 功能描述:扫描工具类
* 作者:唐泽齐
*/
public class ScanUtil {
public static extends Object> void scanList(String scan, Class clazz, List list) throws Throwable {
Stream walk = Files.walk(Paths.get(scan));
walk
.filter(Files::isRegularFile)
.map(path ->
path.toString().replaceAll(new String("\\\\"), ".").replaceAll("src.", "")
)
.filter(p -> p.endsWith(".java")).map(p ->
{
try {
return Class.forName(p.replaceAll(".java", ""));
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
)
.filter(Objects::nonNull)
.filter(p -> clazz.isAssignableFrom(p))
.map(p -> {
try {
return p.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}).filter(Objects::nonNull)
.forEach(p -> {
list.add((T) p);
});
}
}
Original: https://www.cnblogs.com/tangzeqi/p/16474893.html
Author: instr
Title: 获取类的子类
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/574711/
转载文章受原作者版权保护。转载请注明原作者出处!