Pergunta

According to http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#getDeclaredMethods%28%29, Class.getDeclaredMethods() should only include methods "declared by the class". However, I am getting some pretty surprising results with the test code below:

import java.util.Arrays;

class A {
 public static A m1() { return null; }
 public static A m2() { return null; }
 public static A m3() { return null; }
}

class B extends A {
 public static A m1() { return null; }
 public static B m2() { return null; }
// public static Object m3() { return null; } won't compile
}


public class Scratch {
 public static void main(final String[] args) {
  System.out.println(Arrays.asList(B.class.getDeclaredMethods()));
 }
}

A few things that look quite strange/surprising to me:

  • The compiler complain about B.m3() having an incompatible return type with A.m3(). This is dictated by JSL 8.4.8.3 (Page 225 v3 langspec-3.0.pdf). But I am curious, why this restriction needs to apply to static methods. My understanding is that static methods can be hidden and not overriden, and that the reference is resolved at compile time, so what is the reasoning behind this restriction?

  • Two m2() methods are included in the output. This appears to contradict the claim that getDeclaredMethods() only returns methods "declared by the class", and "excludes inherited methods". I don't see A.m2() as "declared by" B.

  • One m1() is included in the output. Following the previous point, if it made sense to let getDeclaredMethods() return two m2(), why doesn't it return two m1() as well? They are after all two distinct methods, and one is hidden by the other. I don't see any fundemental difference between the case of m1() and m2() except the return type being the same in the case of m1(), but the return type as I understand is not part of the method signature?

Thanks in advance!

Foi útil?

Solução

See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6815786

Though it had been reported against 1.6.0_12-b04 on 2009-03-11 05:44:57.0 but Sun accepted it on 2010-07-22 01:25:56.0

in brief:

Synopsis (reflect) Class.getDeclaredMethods() is returning inherited methods

Category java:classes_lang

Reported Against

State 3-Accepted, bug

Priority: 3-Medium

Submit Date 11-MAR-2009

Work Around N/A

Evaluation Will investigate.

Posted Date : 2010-07-22 01:25:56.0

Outras dicas

I can confirm that the bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6815786 is still present in Oracle Java Windows 64-bit 1.6.0_35.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top