如何传递带注释的Object?

时间:2014-07-28 02:54:57

标签: java android

我尝试使用带注释的类作为参数,如下所示:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ContextHolder {
}

@ContextHolder
class Foo extends Context {
}

// In some other place
protected Context getContext(ActionHandler handler) {
    if (handler.getClass().isAssignableFrom(Context.class)) {
        return (Context) handler;
    }
    for (Method m : handler.getClass().getDeclaredMethods()) {
        if (m.getReturnType().isAssignableFrom(Context.class)) {
            try {
                return (Context) m.invoke(handler);
            } catch (IllegalAccessException e) {
                ALog.w("", e);
            } catch (IllegalArgumentException e) {
                ALog.w("", e);
            } catch (InvocationTargetException e) {
                ALog.w("", e);
            }
            break;
        }
    }
    ALog.e("Can't find Context in passed ActionHandler");
    return null;
}

Foo foo = ...;
getContext(foo?)

问题是我不知道如何致电getContext()。简单地传递foo会导致编译错误。

任何提示都将受到赞赏。谢谢!

0 个答案:

没有答案