以下のJavaコードをコンパイルすると、
[Cannot refer to the non-final local variable target defined in an enclosing scope]
というエラーが発生します。
java
1package mytest.gui; 2 3import java.util.ArrayList; 4import java.util.Collection; 5import java.util.List; 6 7import org.apache.commons.collections4.CollectionUtils; 8import org.apache.commons.collections4.ListUtils; 9import org.apache.commons.collections4.Predicate; 10 11public class Console { 12 13 public static void main(String[] args) { 14 List<String> list = new ArrayList<String>(); 15 list.add("maeda"); 16 list.add("oshima"); 17 list.add("shinoda"); 18 List<String> selectedList = select(list, "shinoda"); 19 } 20 21 /** 22 * 文字列に一致するListを生成する 23 * @param list 検索対象のList 24 * @param target 絞り込み対象の文字列 25 */ 26 private static List<String> select(List<String> list, String target) { 27 return ListUtils.select(list, new Predicate<String>() { 28 public boolean evaluate(String elm) { 29 return elm.contains(target); 30 } 31 }); 32 } 33} 34
xml
1<!-- pom.xml --> 2<dependency> 3 <groupId>org.apache.commons</groupId> 4 <artifactId>commons-collections4</artifactId> 5 <version>4.0</version> 6</dependency>
エラーメッセージの通り、引数をfinal String target
にすると、エラーは出なくなりました。
英語メッセージの和訳は、「finalでないローカル変数は、エンクロージングスコープで参照できない」です。
なぜ、final修飾子を付けないと参照できないのでしょうか?
よろしくお願いします。
実行環境
- Java7
- Eclipse4.5
- Commons-Collections 4.0
補足
Java8ではエラーは出ませんでした。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/18 09:45