今天還是沒事看了看elfinder源碼,發現之前說的兩個版本實現都是基於不同的jdkelfinder源碼瀏覽-Volume文件系統操作類(1),
帶前端頁面的是基於1.6中File實現,另一個是基於1.7中的Path實現,
今天看了一個非常有意思的匿名類應用,先看基礎java中一個引人深思的匿名內部類
其中引起我注意的是一個文件搜索的實現,
項目代碼並沒有引起我的問題,但深思的是基於1.8源碼的實現使用了一個
@@@@@DirectoryStream.Filter<Path>接口,此接口是一個包裝接口,使用了java1.8中的接口函數式方法@FunctionalInterface@@@@@@@@@@@@@@@@
請先參考java1.7中新增的NIOJAVA NIO:Path ,File
首先先看一看此方法應用,此方法獲取給定的工作空間中非隱藏的文件列表,
包裝Volume類
@Override public Target[] listChildren(Target target) throws IOException { //其中這裏使用了一個NioHelper工具類封裝了之前定義的Path接口,來獲取非隱藏文件 List<Path> childrenResultList = NioHelper.listChildrenNotHidden(fromTarget(target)); List<Target> targets = new ArrayList<>(childrenResultList.size()); for (Path path : childrenResultList) { targets.add(fromPath(path)); } return targets.toArray(new Target[targets.size()]); }
令人深思的是下面我們它的實現
NIOHelper類
此類是我今天看到的一個匿名接口使用
/** * Gets children paths from the give directory (excluding hidden files). * 帶有文件過濾的 * @param dir path to the directory. * @return the children paths from the give directory. * @throws IOException if something goes wrong. */ public static List<Path> listChildrenNotHidden(Path dir) throws IOException { // not hidden file filter
// DirectoryStream.Filter<Path> notHiddenFilter = new DirectoryStream.Filter<Path>() { public boolean accept(Path path) throws IOException { return !Files.isHidden(path); } };
//調用了同級類中的方法listChildren return listChildren(dir, notHiddenFilter); }
/** * Gets children paths from the give directory appling the given filter. * 依據NIO中Files類中newDirectoryStream方法傳入一個
DirectoryStream.Filter接口來判斷是否是隱藏目錄,如果是就捨棄,不是就加入一個list中,
然後使用Collrctions中的unmodifiableList設置此list不可更改,
通過判斷傳入的dir來讓Collrctions中emptyList方法設置返回的list是否是一個空的
* @param dir path to the directory. * @param filter the filter to be applied * @return the children paths from the give directory. * @throws IOException if something goes wrong. */
public static List<Path> listChildren(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException {
if (isFolder(dir)) { List<Path> list = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = (filter != null ? Files.newDirectoryStream(dir, filter) : Files.newDirectoryStream(dir))) { for (Path p : directoryStream) { list.add(p); } } return Collections.unmodifiableList(list); } return Collections.emptyList(); }
至此我們已經看完了這個實現的具體應用,發現原來匿名類是如此的強大,完全少寫很多之前寫代碼中的邏輯判斷