BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #12274同步于 2009/11/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

问个关于反射的问题

martree
2009/11/19镜像同步2 回复
在jdkdoc中关于getDeclaredMethod有这样一段话 public Method getDeclaredMethod(String name, Class<?>... parameterTypes) If more than one method with the same parameter types is declared in a class, and one of these methods has a return type that is more specific than any of the others, that method is returned; otherwise one of the methods is chosen arbitrarily. 这个大概意思是说如果一个类中定义了多个含有相同参数类型的方法,并且如果它们中的一个方法的返回类型有着更为确切的返回类型,则这个方法被返回,否则随机选一个返回。 我想问的是,get的方法的第一个参数指定了方法的名字,而在一个类中同一个方法名的参数是不会相同的,那么上面所说的那种情况何时会发生,有人遇到过吗? 或者我的理解有问题><
订阅后,新回复会通过你的通知中心匿名送达。
2 条回复
YangYu机器人#1 · 2009/11/20
想特殊情况想了半天居然没想出来,可能是平常没用到的关系╮( ̄﹏ ̄)╭ 往继承多态那块儿想去了,方向错了?等待大牛来解释……
martree机器人#2 · 2009/11/20
【 在 YangYu 的大作中提到: 】 : 想特殊情况想了半天居然没想出来,可能是平常没用到的关系╮( ̄﹏ ̄)╭ : 往继承多态那块儿想去了,方向错了?等待大牛来解释…… 感谢, 费了半天劲,绕了个大圈,在jdkdoc中找到了解释,如下: Note that there may be more than one matching method in a class because while the Java language forbids a class to declare multiple methods with the same signature but different return types, the Java virtual machine does not. This increased flexibility in the virtual machine can be used to implement various language features. For example, covariant returns can be implemented with bridge methods; the bridge method and the method being overridden would have the same signature but different return types. 这里头有很深的机制,简要说就是对于java语言,同一个类中名字和参数相同的方法会产生冲突,即使返回值不同;但是对于jvm确认为如果只是返回值不同,它们完全可以构成overloaded的关系,因此会出现我所迷惑的问题。 你可以google 'covariant return type'和'bridge methods',注意这个不是bridge pattern。 正常是无法调用bridge method的,只能通过反射,因此调用getDeclaredMethods()是会产生这个问题。 例子我正在写,待会有时间就发过来。 这是在JDK5之后加入的。