重写 File 类 toString 而无需在重写类类型中创建对象

我有一个ArrayList要打印到控制台的文件。我toString()对类的方法很好,ArrayList但我不想打印File对象的路径名,我不想像调用getName()方法时那样打印它们的名称.


我想像这样简单地做到这一点:


class overridingClass extends File {

    @Override

    public String toString() {

        return Super.getName();

    }

}

有没有办法以某种方式覆盖 FiletoString()方法而不必将我的File对象更改为overridingClass对象


PS:我已经为此搜索了几个小时,甚至找不到关于覆盖内置类方法的任何内容,所以如果有人可以在找不到任何相关内容的情况下进行问答,那就太好了,而且可能在这里放一个链接


宝慕林4294392
浏览 303回答 1
1回答

翻翻过去那场雪

试图将自定义打印方法直接绑定到File对象违反了单一职责原则。可能有多种有效的方法来打印列表的内容。将每个打印方法直接添加到类中会很快使类膨胀,也会使类的用户感到困惑。最实用的方法是创建一个单独的对象或实用方法来执行这项工作。public class FileNamePrinter {&nbsp; &nbsp; public String print(List<File> files) {&nbsp; &nbsp; &nbsp; &nbsp; StringJoiner joiner = new StringJoiner("," "[", "]");&nbsp; &nbsp; &nbsp; &nbsp; for (File file : files) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; joiner.add(file.getName());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return joiner.toString();&nbsp; &nbsp; }}在您的常规逻辑中,您现在可以使用此FilePrinter对象来执行翻译。List<File> files = ...;FileNamePrinter printer = new FileNamePrinter();System.out.println(printer.print(files));另一种选择是根据该getName方法将文件列表转换为字符串列表,然后打印该列表System.out.println(files.stream()&nbsp; &nbsp; .map(File::getName)&nbsp; &nbsp; .collect(Collectors.toList()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java