父類:
package test; public class FatherClass { protected int i=0; }
子類:
package test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Child extends FatherClass { public int i1=1; public void function(){ System.out.println("call Child1 function"); } public static void main(String []args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ //開始執行main System.out.println("the entrance."); System.out.println("----------------"); //父類引用指向子類對象實例 FatherClass f; f=new Child(); //f.function();//不符合語法規則,編譯不通過 System.out.println(f); System.out.println(f.getClass()); System.out.println("----------------"); //子類引用指向子類對象實例 Child c1; c1=(Child) f; c1.function(); System.out.println(c1); System.out.println(c1.getClass()); //運行時通過Method調用方法 Method m=Child.class.getMethod("function"); m.invoke(f);//輸出正常 //子類引用指向了父類實例,父類中並沒有void function() //編譯正確但是運行錯誤 Child c2=(Child) new FatherClass(); m.invoke(c2);//Exception /** * Exception in thread "main" java.lang.ClassCastException: * test.FatherClass cannot be cast to test.Child1 at test.Child1.main(Child1.java:36) */ } }
輸出:
the entrance.
----------------
test.Child@2a139a55
class test.Child
----------------
call Child1 function
test.Child@2a139a55
class test.Child
call Child1 function
Exception in thread "main" java.lang.ClassCastException: test.FatherClass cannot be cast to test.Child
at test.Child.main(Child.java:37)