说我有以下代码...如何测试Method是否接受参数类型?
@FunctionalInterface
static interface MessageFunction<T> {
void send(T obj);
}
static @interface Message {
Class<?> value();
}
static class Foo {
@Message(String.class)
MessageFunction<String> bass = (string) -> {
// Do Stuff
};
}
static class MessageManager {
Map<Class<?>, MessageFunction<?>> messages = new HashMap<>();
public void register(Object obj) {
for (Field field : obj.getClass().getDeclaredFields()) {
Message message = field.getAnnotation(Message.class);
if (message != null) {
MessageFunction<?> function;
try {
function = (MessageFunction<?>) field.get(obj);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
return;
}
Method sendMethod;
try {
// Will this work?
sendMethod = function.getClass().getDeclaredMethod("send", Object.class);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
return;
}
// How do I do something like this?
/*if (sendMethod.testParamaters(message.value())) {
this.messages.put(message.value(), function);
}*/
}
}
}
}
public static void main(String[] args) {
MessageManager manager = new MessageManager();
manager.register(new Foo());
}
我反映引用泛型类型的@FunctionalInterface
的字段。因为方法参数也是通用的,所以我无法知道它接受哪些参数,因此我必须通过其他方法(注释)传递它。
问题是存在注释值和泛型类型不必匹配,似乎无法检查。如果在注释中列出的类型不会被接收到发送方法中,我不会注册失败。
我怎么去关于这个东西,而实际上并没有调用这个方法。有没有办法?更好的是,尽管我知道它最可能不可能,但是有没有办法知道没有注解的参数类型是什么?
可能的复制[获取运行时泛型类](http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime)。基本上答案是lambda的“不能完成”。 – Radiodef 2015-02-08 07:26:28
我知道有关在运行时获取泛型类型的其他问题的答案。然而,这些解决方案似乎没有工作时处理一个泛型功能接口的lambda – 2015-02-08 21:43:35
我发现[TypeTools](https://github.com/jhalterman/typetools)提到的是另一个关于堆栈溢出的问题。虽然它不直接解决我所问的问题,但它解决了我的特殊问题。 – 2015-02-09 06:13:47