public class Test extends Object implements Cloneable{

public static void main(String[] args) throws Exception{
Test t=new Test();
t.clone();
System.out.println("-------------");
Method method=t.getClass().getMethod("clone", null);
                System.out.println(method.getModifiers());
}

}可以看到,执行clone方法,没有任何问题,但是通过反射获取时却得到 java.lang.NoSuchMethodException错误,
如何解释呢?
PS:JDK1.5

解决方案 »

  1.   

    多加一个覆盖Object的clone方法,内容super.clone()
      

  2.   

    Class.getMethod(...)只是获取本类Class对象上所定义的public 方法.注意只是本类,不包括父类的public方法.如果要获取protecd方法可以用Class.getDeclaredMethod("...").如果要获取取父类的public方法: Class.getSuperclass().getMethod(..);如果要获取父类protecd方法:Class.getSuperclass().getDeclaredMethod("...");
      

  3.   

    to 楼上朋友
      
      谢谢你的回答,不过好像你不小心说反了,  如果要获取public方法可以用Class.getDeclaredMethod("...").  如果要获取取父类的protecd方法: Class.getSuperclass().getMethod(..); 另外,对于hashCode等superClass的方法是可以直接通过自己的class对象反射得到,并不需要通过superClass对象,为什么clone不行呢?仅仅是因为protected关键字吗?因为是在类本身中通过本身的class对象调用的,protected关键字应该不会发挥作用的,效果和public一样的。盼更为详细的解答
      

  4.   

    问题找到了。
    由于clone()是protected的,但是getMethod()只能获得public类型的方法,所以楼主必须用getDeclaredMethod来获得protected类型的方法,源代码改成下面这样:import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;public class Test extends Object implements Cloneable {  public static void main(String[] args) throws Exception {
        Test t = new Test();
        t.clone();
        System.out.println("-------------");
        Class c1 = t.getClass();
        Method method =
            t.getClass().getSuperclass().getDeclaredMethod("clone", null);
        System.out.println(method.getModifiers());
      }
    }
      

  5.   


    Method method = t.getClass().getSuperclass().getDeclaredMethod("clone", null);
      

  6.   

    楼主也可以把

    extends Object去掉,但implements Cloneable不能去。