我尝试使用带注释的类作为参数,如下所示:
@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会导致编译错误。
任何提示都将受到赞赏。谢谢!