gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:16:13 25 4
gpt4 key购买 nike

我正在尝试将对象变量转换为可能的各种其他类。对于此示例,我使用字符串...

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());
}

输出:

I'm an Object: Hello World
I'm a String: Hello World

为什么两个输出都不是字符串版本?

最佳答案

这里有一个重载方法,whatsThis

对于重载方法,方法调用是在编译时绑定(bind)的。因此编译器不知道 cast() 方法将返回什么对象。它只知道declared return type它与 Class.forName() 的返回类型匹配,即 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));

关于java - String.class.cast(var) 与 Class.forName ("java.lang.String").cast(var),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com