gpt4 book ai didi

java 。引用不带参数的方法

转载 作者:行者123 更新时间:2023-11-30 06:16:45 25 4
gpt4 key购买 nike

我在理解 Java 8 时遇到一个问题,即与将方法引用作为静态方法的参数相关的问题。在我的代码中,我找不到如何发送对没有任何参数并且必须是确定类的对象的方法的方法的引用。

所以,我希望发送给静态函数的方法可以用于静态方法中的对象。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

interface FuncForPath<T> {
T func(T path);
}

class MethodsForFolder {

public static void printFilesInFolder(Path path, FuncForPath<Path> funcPath) {
Stream<Path> paths = null;
try {
paths = Files.list(path);
} catch (IOException e) {
System.out.println(
"The problems have been appeared during reading folder: " + path.toAbsolutePath().toString());
e.printStackTrace();
}
System.out.println("Files list in folder:" + path.toAbsolutePath().toString());
paths.forEach(p -> funcPath.func(p).toString()); // I don't know to how to write this code to perform
}
}

public class TestRefToIntance {

public static String testWindowsFloder = "C://Logs";

public static void main(String[] args) {

Path path = Paths.get(testWindowsFloder);
// I want that this 2 methods are performed depending on transfered methods
// reference
MethodsForFolder.printFilesInFolder(path, Path::toAbsolutePath);
MethodsForFolder.printFilesInFolder(path, Path::getFileName);
}
}

最佳答案

尝试Function<Path, Path>而不是FuncForPath 。这将需要一个采用 Path 的方法。参数并返回 Path 。请注意,实例方法始终具有“不可见”this参数,因此Path::getFileName与该签名匹配。

然后您可以这样调用它:paths.forEach( p -> funcPath.apply( p ).toString() ); (尽管您没有对返回的字符串执行任何操作,所以您可能想调用 paths.map( f ).map( Path::toString ).collect( someCollector );

关于 java 。引用不带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49030688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com