Class问题

今天一个同学问了我下面程序的main方法中的第二行代码和注释中的两行代码表达的意思完全相同,注释中的两行代码不能通过编译(这很容易理解),而第二行(采用方法调用链)却可以顺利通过编译(这就很难理解了)。
public class Test
{
    public void func()
    {
         System.out.println("func");
   }
 
   public static void main(String args[]) throws Exception
   {
           Object obj = new Test();

           //下面这行可以成功编译 
           ((Test)obj).getClass().newInstance().func();

           //下面这两行无法通过编译
           /*Class c = ((Test)obj).getClass();
           c.newInstance().func(); */
  
 }
}

感谢论坛高手的帮助,我基本上明白了上述问题的原因。-----------------------------------------------------------------------------------------------------------------------

paulex 发表于2006-11-08 08:09:00  IP: 10.0.0.*
因为Generic, 编译器可以在编译期获得类型信息所以可以编译这类代码。你将下面那两行改成

Class<? extends Test> c = ((Test)obj).getClass();
c.newInstance().func();

应该就能通过编译了。

楼上的用1.4.2的编译器所以不能编译。
-------------------------------------------------------------------------------------------------------------------------
在JDK 1.5中引入范型后,Object.getClass()方法的定义如下:
public final Class<? extends Object> getClass()
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Returns:
The java.lang.Class object that represents the runtime class of the object. The result is of type Class<? extends X> where X is the erasure of the static type of the expression on which getClass is called.
这说明((Test)obj).getClass()语句返回的对象类型为Class<? extends Test>,而Class<T>的newInstance()方法的定义如下:
public T newInstance() throws InstantiationException,IllegalAccessException
即对于编译器看来,Class<Test>的newInstance()方法的对象类型为Test,而((Test)obj).getClass()返回的为对象类型为Class<? extends Test>,所以,编译器认为((Test)obj).getClass().newInstance()返回的对象类型为Test。

下面这两行代码之所以无法通过编译
           Class c = ((Test)obj).getClass();
           c.newInstance().func();
是因为((Test)obj).getClass()返回的为对象类型为Class<? extends Test>,但是我们在第一行将结果强制转换成了Class,然后再去调用Class的newInstance方法,而不是去调用Class<Test>的newInstance方法,编译器当然不再认为Class的newInstance方法返回的对象为Test了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值