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
谢谢你的回答,不过好像你不小心说反了, 如果要获取public方法可以用Class.getDeclaredMethod("..."). 如果要获取取父类的protecd方法: Class.getSuperclass().getMethod(..); 另外,对于hashCode等superClass的方法是可以直接通过自己的class对象反射得到,并不需要通过superClass对象,为什么clone不行呢?仅仅是因为protected关键字吗?因为是在类本身中通过本身的class对象调用的,protected关键字应该不会发挥作用的,效果和public一样的。盼更为详细的解答
由于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());
}
}
Method method = t.getClass().getSuperclass().getDeclaredMethod("clone", null);
extends Object去掉,但implements Cloneable不能去。