如题,按说java是值传递的,可下面的代码能正确运行,getClassSet方法中有一个局部的set变量,在doAddClass方法里对其进行了add但没有返回,但最后却能从getClassSet方法返回的set里获取到元素,这是为什么?代码略长,劳烦大佬了
/**
* 获取指定包名下的所有类文件,可读取class或jar
* Enumeration古代迭代器
*/
public static Set<Class<?>> getClassSet(String packageName) {
Set<Class<?>> classes = new HashSet<>();
try {
//获取文件系统下的资源文件,url路径类似 file:/C:/Users/Kaibo/OneDrive/workplaceForIDEA/SmartFramework/target/classes/com/smar4j/framework/util
Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (null != url) {
String protocol = url.getProtocol();
//判断url协议,file还是jar
if ("file".equals(protocol)) {
//替换url中的空格
String packagePath = url.getPath().replaceAll("%20", "");
addClass(classes, packagePath, packageName);
} else if ("jar".equals(protocol)) {
//操作jar文件
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
if (null != jarURLConnection) {
JarFile jarFile = jarURLConnection.getJarFile();
if (null != jarFile) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.endsWith(".class")) {
String className = name.substring(0, name.lastIndexOf(".")).replaceAll("/", ".");
doAddClass(classes, className);
}
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
private static void addClass(Set<Class<?>> classes, String packagePath, String packageName) {
File[] files = new File(packagePath).listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
}
});
for (File file : files) {
String fileName = file.getName();
//如果不是目录
if (file.isFile()) {
String className = fileName.substring(0, fileName.lastIndexOf("."));
if (StringUtil.isNotEmpty(packageName)) {
className = packageName + "." + className;
doAddClass(classes, className);
} else {
String subPackagePath = fileName;
if (StringUtil.isNotEmpty(packagePath)) {
subPackagePath = packagePath + "/" + subPackagePath;
}
String subPackageName = fileName;
if (StringUtil.isNotEmpty(packageName)) {
subPackageName = packageName + "." + subPackageName;
}
addClass(classes, subPackagePath, subPackageName);
}
}
}
}
private static void doAddClass(Set<Class<?>> classes, String className) {
Class<?> cls = loadClass(className, false);
classes.add(cls);
}
对于对象来说,传递的只是引用,不是以副本形式(值)传递的,8 种基本类型(非对应的类类型)才是传值。