Java 8中的typeof [英] typeof in Java 8

查看:1051
本文介绍了Java 8中的typeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要检查javascript中变量的数据类型,可以使用 typeof 运算符.

If we want to check the datatype of variable in javascript, we can use typeof operator .

var c = 'str' ;
console.log(typeof(c)); // string
c = 123 ;
console.log(typeof(c)); // number
c =  {} ;
console.log(typeof(c)) ; // object

我想在 Java 8 中实现相同的功能.Java没有typeof运算符,但是有 instanceof 运算符可以检查类型.

I want to achieve the same functionality in Java 8 . Java does not have typeof operator but there's the instanceof operator to check the types.

System.out.println("str" instanceof String);  // true 

Integer a  = 12 ;
System.out.println(a instanceof Integer);


Float f = 12.3f
System.out.println(f instanceof Float); // true

我们能做得更好吗?另外, instanceof 不支持基本类型.

Can we do any better ? Plus instanceof does not support primitive types .

java 8 中是否有任何方法?任何相关的方法将不胜感激.

Is there any approaches in java 8 ? Any relevant approaches will be appreciated.

推荐答案

您可以使用

You can use the getClass() method to get the type of the object you are using:

Object obj = null;
obj = new ArrayList<String>();
System.out.println(obj.getClass());

obj = "dummy";
System.out.println(obj.getClass());

obj = 4;
System.out.println(obj.getClass());

这将产生以下输出:

class java.util.ArrayList
class java.lang.String
class java.lang.Integer

如您所见,它将显示变量引用的对象的类型,该类型可能与变量的类型不同(在本例中为 Object ).

As you see it will show the type of the object which is referenced by the variable, which might not be the same as the type of the variable (Object in this case).

对于基本类型,没有可用的解决方案,因为不知道存储在变量中的类型的问题.基本类型变量只能保存该类型的 值.由于必须在某个位置定义变量(或参数),因此您已经知道它的类型及其可以保存的值.可以使用与 Object 类型相似的基本值的基本"类型,而 Object 类型是Java中所有对象的基本类型.

For primitive types there is no solution available as the problem of knowing the type stored in a variable does not exist. A primitive type variable can hold only values of that type. As you have to define the variable (or parameter) somewhere you already know the type of it and the values it can hold. There is no "base" type for primitive values which you can use similar to the Object type, which is the base type for all objects in java.

这篇关于Java 8中的typeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆