简体   繁体   中英

variable scope inside of parametrized method - java generics

why is it that inside this foreach loop, elem is not recognized as a Path, which it is, and I can only call Object methods on it?

public class TypeOption<Path> implements Option<Path> {

    @Override
    public void apply(String arg, Collection<Path> c) {
        for (Path elem : c) {
            if (Files.isExecutable(elem)) c.remove(elem);
        }
    }
}

this line

if (Files.isExecutable(elem)) c.remove(elem);

is causing the trouble, it says

The method isExecutable(java.nio.file.Path) in the type Files is not applicable for the arguments (Path)

It's because Path is a type parameter here - you've declared a generic type, with Path as the type parameter. I suspect you *wanted:

public class TypeOption implements Option<Path> {

At that point, Path refers to the existing type called Path , and is used for the type argument to Option<T> (or whatever the type parameter is for Option ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM