反射、Java8ストリーム、およびIntelliJに問題があります。IntelliJはオブジェクトを適切なクラスタイプではなくストリームで表示します
Optional<Class> optionalAnnotationClass=...; // some initialization here
Map<Object, Object> anotherMap=new Hashmap();
Class sourceClass = MyClass.class;// some class
Arrays.asList(sourceClass.getDeclaredFields()).stream()
.filter(field -> (!optionalAnnotationClass.isPresent() || Objects.nonNull(field.getAnnotation(optionalAnnotationClass.get()))))
.filter(field -> filterFieldClass.length == 0 || Arrays.asList(filterFieldClass).contains(field.getType()))
.map(field -> doSomething(sourceClass, field))
.filter(Objects::nonNull)
.forEach(entry -> anotherMap.put(entry.getKey(), entry.getValue()));
しかしIntelliJ15がライン
.filter(field -> filterFieldClass.length == 0 || Arrays.asList(filterFieldClass).contains(field.getType()))
のように、それは、
field
は
Object
ではなく最初の
filter
後に開始
Field
であることを訴えて開始し、次のメッセージ
で私を悩まします
プロジェクトのバージョンを確認しましたが、それはウィットです1.8をターゲットとし、JDK8を使用します。キャッシュを無効にしてIntelliJを再起動しました。
どういうところが間違っていますか?
は、ここで私は、最初のフィルタは、JDKに好かれていない理解していない、このような理由から完全
package com.ladop;
import com.google.common.base.CaseFormat;
import com.google.common.collect.Maps;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
public class StaticReflectionUtils {
public static Map<String, Object> extractStaticField(final Class<?> sourceClass,
final Optional<Class> optionalAnnotationClass,
final Class<?>... filterFieldClass) {
final Map<String, Object> fieldNameToValue = new HashMap<>();
Arrays.stream(sourceClass.getDeclaredFields())
.filter(field -> !optionalAnnotationClass.isPresent() || Objects.nonNull(field.getAnnotation(optionalAnnotationClass.get())))
.filter(field -> filterFieldClass.length == 0 || Arrays.asList(filterFieldClass).contains(field.getType()))
.map(field -> extractFieldKeyValue(sourceClass, field))
.filter(Objects::nonNull)
.forEach(entry -> fieldNameToValue.put(entry.getKey(), entry.getValue()));
return fieldNameToValue;
}
public static Map.Entry<String, Object> extractFieldKeyValue(final Class<?> sourceClass,
final Field field) {
field.setAccessible(true);
try {
final String fieldName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field.getName());
return Maps.immutableEntry(
concatenate(sourceClass.getSimpleName(), fieldName), field.get(null));
} catch (IllegalAccessException e) {
}
return null;
}
protected static String concatenate(final String prefix, final String word) {
return new StringBuilder()
.append(prefix)
.append("_")
.append(word).toString();
}
}
IJとは対照的に永続的なビルドツールを使用するとコンパイルできますか?そうでない場合、コードは間違っています。おそらく、あなたはsourceClassのタイプとしてClassを意味するでしょうか? –
bmargulies
@bmargulies良い提案。コマンドラインでmvn clean installを実行すると、同じエラーが発生するので、IntelliJではありません。 sourceClassのタイプが重要なのはなぜですか?私はフィールドを抽出し、それらを反復処理しています。 –
@bmarguliesが固定されています(回答を参照)。しかし、私は何が問題なのか理解できません! JDKの問題? –