在Java 8中的typeof

huangapple go评论83阅读模式
英文:

typeof in Java 8

问题

如果我们想要在JavaScript中检查变量的数据类型,我们可以使用 typeof 运算符。

考虑以下代码片段

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 运算符来检查类型。

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 不支持原始类型。

Java 8 中是否有任何方法?任何相关的方法都将受到赞赏。

英文:

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

Consider this snippet

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

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

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

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

答案1

得分: 23

你可以使用 getClass() 方法来获取你正在使用的对象的类型:

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)不同。

对于基本类型,没有可用的解决方案,因为不存在了解析存储在变量中的基本类型的问题。基本类型变量只能持有该类型的值。由于你必须在某个地方定义变量(或参数),所以你已经知道它的类型及其可能持有的值。与 Object 类型类似的“基础”类型并不存在于基本值,Object 类型是 Java 中所有对象的基础类型。

英文:

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

Object obj = null;
obj = new ArrayList&lt;String&gt;();
System.out.println(obj.getClass());

obj = &quot;dummy&quot;;
System.out.println(obj.getClass());

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

This will generate the following output:

<!-- language: none -->

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

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).

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.

答案2

得分: 8

感谢 @Progman 提供的 getClass() 方法。

class check{

    static Class typeof(Integer a)
    {
        return a.getClass();
    }
    static Class typeof(Character c)
    {
        return c.getClass();
    }
    static Class typeof(Float f)
    {
        return f.getClass();
    }
    static Class typeof(Double d)
    {
        return d.getClass();
    }
    static Class typeof(Long l)
    {
        return l.getClass();
    }
    static Class typeof(String s)
    {
        return s.getClass();
    }

}

因此,现在我们可以检查基本类型和非基本类型

> check.typeof(12) ; // class java.lang.Integer
>
> check.typeof(12.23f) ; // class java.lang.Float
>
> check.typeof('c') ; // class java.lang.Character
>
> check.typeof("str") ; // class java.lang.String

英文:

Thanks to @Progman for getClass() method .

class check{

    static Class typeof(Integer a)
    {
        return a.getClass();
    }
    static Class typeof(Character c)
    {
        return c.getClass();
    }
    static Class typeof(Float f)
    {
        return f.getClass();
    }
    static Class typeof(Double d)
    {
        return d.getClass();
    }
    static Class typeof(Long l)
    {
        return l.getClass();
    }
    static Class typeof(String s)
    {
        return s.getClass();
    }

}

So now we check both primitive and non- primitive types

> check.typeof(12) ; // class java.lang.Integer
>
> check.typeof(12.23f) ; // class java.lang.Float
>
> check.typeof(&#39;c&#39;) ; // class java.lang.Character
>
> check.typeof(&quot;str&quot;) ; // class java.lang.String

答案3

得分: 4

以下是翻译好的部分:

这是我在Java(10或更高版本)中找到的与您的JavaScript示例最接近的功能示例,其中涉及typeof运算符和var(仅在Java中用于局部变量声明)。

它处理原始数据类型,并暗示将原始类型转换为对象,然后在相应的对象上调用.getClass().getSimpleName()方法。

参考文献:使用getClass().getSimpleName()检查Java变量的类型

public class Main {
    public static void main(String[] args) {
        var myNum = 72;
        System.out.println(((Object) myNum).getClass().getSimpleName()); // Integer
        var myInput = 10.52f;
        System.out.println(((Object) myInput).getClass().getSimpleName()); // Float
        var yetAnotherInput = 0.345678923;
        System.out.println(((Object) yetAnotherInput).getClass().getSimpleName()); // Double
        var otherInput = 1_234_567_764_456_211L;
        System.out.println(((Object) otherInput).getClass().getSimpleName()); // Long
        var myName = "John";
        System.out.println(((Object) myName).getClass().getSimpleName()); // String
        var myLetter = 'j';
        System.out.println(((Object) myLetter).getClass().getSimpleName()); // Character
        var myAnswer = true;
        System.out.println(((Object) myAnswer).getClass().getSimpleName()); // Boolean
    }
}
英文:

This is the closest functionality example I could find in Java (10 or higher) to your JavaScript example with the typeof operator and var (local variable declaration only in Java).

It deals with primitive data type and implies casting the primitive to Object first and then calling the .getClass().getSimpleName() method on the respective Object.

References: Use getClass().getSimpleName() to Check the Type of a Variable in Java

public class Main {
public static void main(String[] args) {
    var myNum = 72;
    System.out.println(((Object) myNum).getClass().getSimpleName()); // Integer
    var myInput = 10.52f;
    System.out.println(((Object) myInput).getClass().getSimpleName()); // Float
    var yetAnotherInput = 0.345678923;
    System.out.println(((Object) yetAnotherInput).getClass().getSimpleName()); // Double
    var otherInput = 1_234_567_764_456_211L;
    System.out.println(((Object) otherInput).getClass().getSimpleName()); // Long
    var myName = &quot;John&quot;;
    System.out.println(((Object) myName).getClass().getSimpleName()); // String
    var myLetter = &#39;j&#39;;
    System.out.println(((Object) myLetter).getClass().getSimpleName()); // Character
    var myAnswer = true;
    System.out.println(((Object) myAnswer).getClass().getSimpleName()); // Boolean
}

}

huangapple
  • 本文由 发表于 2020年4月8日 23:47:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61104708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定