2016-05-23 15 views
1

注釈を学習し、学習タスクの1つで、@Cacheという注釈付きキャッシュの実装に、@InjectCacheと注釈を付けたフィールドを挿入する必要があります。注釈パラメータを解決できません

私はこのコードを書いたが、式cache.getAnnotation(Cache.class).name()ではcannot resolve symbol name()がエラーになるが、エラーなしでfield.getAnnotation(InjectCache.class).name()の文字列が先に解決される。

@Cache@InjectCacheの両方がパラメータname()を持っており、彼らは唯一の違いは@TARGET注釈です。

package annotations; 

    import annotations_test.MapCache; 
    import annotations_test.SortedMapCache; 
    import java.lang.reflect.Field; 
    import java.lang.reflect.Type; 
    import java.util.ArrayList; 
    import java.util.List; 

    public class Injector { 
     public static void inject(Object instance){ 
      List<Field> fields = new ArrayList<Field>(); 
      List<Class> caches; 
      caches = addAllCaches(); 
      fields = getAnnotatedFields(fields, instance.getClass()); 
      try { 
      for (Field field : fields) { 
       field.setAccessible(true); 
       String name = field.getAnnotation(InjectCache.class).name(); 
       Boolean implementation_not_found = true; 
       for (Class cache: caches){ 

         if (name.equals(cache.getAnnotation(Cache.class).name())){ 
          implementation_not_found = false; 
          field.set(instance, cache.newInstance()); 

         } 
       } 
       if (implementation_not_found){ 
        throw new TypeNotPresentException(Cache.class.getTypeName(),null); 
       } 

      } 
      }catch (TypeNotPresentException e){ 
       e.printStackTrace(); 
      } catch (InstantiationException e) { 
       e.printStackTrace(); 
      } catch (IllegalAccessException e) { 
       e.printStackTrace(); 
      } 
     } 

これは@Cacheは、次のようになります。

package annotations; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 



@Target(value= ElementType.TYPE) 
@Retention(value= RetentionPolicy.RUNTIME) 
public @interface Cache { 
    String name(); 
} 

そして@InjectCache

package annotations; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 



@Target(value= ElementType.FIELD) 
@Retention(value= RetentionPolicy.RUNTIME) 
public @interface InjectCache { 
    String name(); 
} 
+0

あなたはあなたのコード切り取らまたはテキスト内のリンクにimport宣言を追加してくださいでした。 – SpaceTrucker

+0

プロジェクトをきれいにして、すべてを再コンパイルしてみてください –

答えて

1

Class cache forループではraw typeあるため、このエラーが発生します。

あなたは(それだけでワイルドカード<?>であっても)ジェネリック型を持つようにそれを変更する必要があります。

for (Class<?> cache: caches) { 
    // ... 
} 

この理由は、あなたが生の型を持つ任意の汎用メソッドを使用することができないということであり、 。ワイルドカードを使用しない場合、戻りタイプはgetAnnotation(Cache.class)Annotationであり、注釈タイプはCacheではありません。

ワイルドカードを追加すると、getAnnotationメソッドがタイプセーフなので、最適なオプションです。あなたもかかわらず、正しい型にキャストすることができます。私たちはあなたが話している注釈かについて正確に知るように

((Cache)cache.getAnnotation(Cache.class)).name() 
+0

ありがとうございました! ジェネリック型に変更すると、 –

関連する問題