gpt4 book ai didi

java - 获取真实的类类型

转载 作者:行者123 更新时间:2023-11-29 06:50:22 27 4
gpt4 key购买 nike

如果我这样做:

String s = "hello";
Class<?> c = s.getClass();

那么 c 实际上是一个 Class 但里面有一个 String。那么我如何得到一个 String 类型呢?

因为如果我使用:c.getClass() 我显然得到了一个 Class 类型。

最佳答案

所以,Class<?> c将引用 String 类型的类的对象。 Class<?> c基本上有一些metadata关于 String 类。

    String s = "hello";
Class<?> c = s.getClass();
String s1 = (String) c.newInstance();

编辑:

因此,在 Class 对象上有几种方法可以用来检索有关 Class 的信息:

    Class#getName() //the name of the class or interface represented by this object with package name
Class#getSimpleName() // returns only the name of the Class

例如:

String s = "hello";
Class<?> c = s.getClass();
System.out.println("Name : "+c.getName());
System.out.println("Simple Name: "+c.getSimpleName());
System.out.println("Canonical Name: "+c.getCanonicalName());
System.out.println("Type Name : "+c.getTypeName());

你会得到输出:

Name : java.lang.String
Simple Name: String
Canonical Name: java.lang.String
Type Name : java.lang.String

注意:如您所见,不同方法(如 getCanonicalName、getCanonicalName 等)获得的返回值相同,可能并不总是相同,请点击我在下面提供的链接了解差异。

除此之外,类对象上有几种方法可用于获取 metadata information。关于 class .请关注docs了解更多信息。

关于java - 获取真实的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50418043/

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