String.class.cast(var)与Class.forName(" java.lang.String")。cast(var)

时间:2015-10-22 18:05:58

标签: java

我试图将一个Object变量强制转换为各种其他类。对于这个例子,我使用String ...

Object msg = "Hello World";
whatsThis(Class.forName("java.lang.String").cast(msg));
whatsThis(String.class.cast(msg));

protected void whatsThis(String elem)
{
  System.out.println("I'm a String: " + elem);
}

public void whatsThis(Object elem)
{
  System.out.println("I'm an Object: " + elem.toString());
}

输出:

  

我是一个对象:Hello World
  我是一个字符串:Hello World

为什么不输出String版本?

1 个答案:

答案 0 :(得分:2)

这里有一个重载方法,whatsThis

对于重载方法,方法调用在编译时绑定。因此编译器不知道cast()方法将返回什么对象。它只知道与Class.forName()的返回类型匹配的declared return type,它是java.lang.Object。

// Here the compiler knows that the object is a string and can bind the
// method call to the String version of the overloaded method.
whatsThis(String.class.cast(msg));

// Here the compiler knows that Class.forName will return some class object, but
// only at runtime is it known that the class will be the string class.  Thus
// the compiler binds to the Object version of the overloaded method.
whatsThis(Class.forName("java.lang.String").cast(msg));