日期:2014-05-20  浏览次数:20796 次

getDeclaredMethods返回父类Method?
为什么getDeclaredMethods会返回父类的Method呢?
Java code

public class ReflectTest {
    
    public static void main(String[] args){
        String name;
        if(args.length > 0) name = args[0];
        else{
            Scanner scanner = new Scanner(System.in);
            name = scanner.next();
        }
        try{
            Class cl = Class.forName(name);
            Class supercl = cl.getSuperclass();
            String modifiers = Modifier.toString(cl.getModifiers());
            if(modifiers.length() > 0)System.out.print(modifiers + " " + name);
            if(supercl != Object.class) System.out.print(" extends " + supercl.getName() + "{\n");
            
        
            //Method
            printMethodsInfo(cl);
            
            System.out.println(")\n");
            
            
        } catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
    }

    static public void printMethodsInfo(Class cl){
        Method[] methods = cl.getDeclaredMethods();
        //Method[] methods = cl.getMethods();
        for(Method m : methods){
            String modifiers = Modifier.toString(m.getModifiers());
            System.out.print("    ");
            if(modifiers.length() > 0) System.out.print(modifiers + " ");
            Class retType = m.getReturnType();
            System.out.print(retType.getName() + " ");
            System.out.print(m.getName() + "(");
            Class[] paramTypes = m.getParameterTypes();
            for(int j = 0; j < paramTypes.length; j++){
                if(j != 0) System.out.print(" ,");
                System.out.print(paramTypes[j].getName());
            }
            System.out.println(");");
        }
    }
}


//测试类
public class MyTest extends ParentTest{
    public void func1(){
        
    }
}
class ParentTest{
    public void func2(){
        
    }
}





结果如下:
  public void func1();
  public volatile void func2();


------解决方案--------------------
我运行出来是正确的,不是超类
按正常来说也是getDclaredMethods()也是该类的方法
你看看是不是你输入dos窗口的类名输错了
------解决方案--------------------
我的运行结果

MyTest
public MyTest extends ParentTest{
public void func1();
)