假设有一个Service接口类,接口有一个方法show(),一个实现类ServiceImpl.
代码:
包名:java.test
Object obj=new ServiceImpl();
Class c=Class.forName("java.test.Service");
System.out.println(c==Service.class); //true
System.out.println(c.equals(Service.class)); //true
Service.class.cast(obj).print(); //正常调用实现类的print方法
c.cast(obj).print(); //无法调用print方法,实际上c.cast(obj)还是一个Object对象
问题在于,c和Service.class不是同样的吗?为什么在调用cast方法对同一个对象进行转换的结果却不同?
代码:
包名:java.test
Object obj=new ServiceImpl();
Class c=Class.forName("java.test.Service");
System.out.println(c==Service.class); //true
System.out.println(c.equals(Service.class)); //true
Service.class.cast(obj).print(); //正常调用实现类的print方法
c.cast(obj).print(); //无法调用print方法,实际上c.cast(obj)还是一个Object对象
问题在于,c和Service.class不是同样的吗?为什么在调用cast方法对同一个对象进行转换的结果却不同?










