Is it possible to get the data type of an input variable (could be any primitive type, int, bool, float, double) returned as a string by using just one line of code? I know this can easily be done for a String type using getName
and getShortName
but I am unsure of how to use these methods to return the type of a primitive type. I also want to keep my code very short for doing this preferably using just one line.
是否可以通过仅使用一行代码获取作为字符串返回的输入变量的数据类型(可以是任何基本类型,int,bool,float,double)?我知道使用getName和getShortName可以轻松地对String类型进行此操作,但我不确定如何使用这些方法返回基本类型的类型。我还希望保持我的代码非常简短,最好只使用一行。
I have searched around and cannot find anywhere this question has been answered in the way I require.
我已经四处搜索,找不到任何地方,这个问题已按我要求的方式得到解答。
1 个解决方案
#1
What about Class.getName()
?
Class.getName()怎么样?
Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification, Second Edition.
以String形式返回此Class对象表示的实体名称(类,接口,数组类,基本类型或void)。如果此类对象表示不是数组类型的引用类型,则返回类的二进制名称,如Java语言规范第二版所指定。
If this class object represents a primitive type or void, then the name returned is a String equal to the Java language keyword corresponding to the primitive type or void.
如果此类对象表示基本类型或void,则返回的名称是一个String,它等于与基本类型或void相对应的Java语言关键字。
You can follow this link in the Java Doc that explain very well how to use this method.
您可以在Java Doc中关注此链接,该链接非常好地解释了如何使用此方法。
#1
What about Class.getName()
?
Class.getName()怎么样?
Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification, Second Edition.
以String形式返回此Class对象表示的实体名称(类,接口,数组类,基本类型或void)。如果此类对象表示不是数组类型的引用类型,则返回类的二进制名称,如Java语言规范第二版所指定。
If this class object represents a primitive type or void, then the name returned is a String equal to the Java language keyword corresponding to the primitive type or void.
如果此类对象表示基本类型或void,则返回的名称是一个String,它等于与基本类型或void相对应的Java语言关键字。
You can follow this link in the Java Doc that explain very well how to use this method.
您可以在Java Doc中关注此链接,该链接非常好地解释了如何使用此方法。