注釈を学習し、学習タスクの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();
}
あなたはあなたのコード切り取らまたはテキスト内のリンクにimport宣言を追加してくださいでした。 – SpaceTrucker
プロジェクトをきれいにして、すべてを再コンパイルしてみてください –