有没有办法检查instanceof基元变量java [英] is there a way to check instanceof primitives variables java

查看:108
本文介绍了有没有办法检查instanceof基元变量java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以通过使用instanceof运算符知道对象引用是一个测试。但是有没有运算符来检查原始类型。例如:

We can know object reference is-a test by using instanceof operator. But is there any operator to check primitive types. For example:

byte b = 10;

现在如果我只考虑价值 10 。有什么方法我可以发现它被声明为一个字节?

Now if I only consider the value 10. Is there any way I could find out that it was declared as a byte?

推荐答案

局部变量



假设你的意思是局部变量,只要在这种情况下作为对象java.lang.Byte传递,原语总是会被它的包装类型自动包装。使用反射引用局部变量是不可能的,因此你无法区分Byte和byte或Integer和int等。

Local variables

Assuming you mean by local variables the primitive will always be automatically wrapped by its wrapper type whenever passed as an object, java.lang.Byte in this case. It's impossible to refer to local variables using reflection so you cannot differentiate between Byte and byte or Integer and int etc.

Object bytePrimitive = (byte) 10;

System.out.println("is a Byte ?   " + (bytePrimitive instanceof Byte));
System.out.println("Check class = " + (bytePrimitive.getClass()));

// false because class in this case becomes Byte, not byte.
System.out.println("Primitive = " + (bytePrimitive .getClass().isPrimitive()));



字段



但是,如果你'重新讨论类中的字段,然后事情就不同了,因为可以获取实际声明类型的句柄。然后,您可以按预期使用java.lang.Class.isPrimitive(),类型将为byte.class。

Fields

However, if you're talking about fields in classes, then things are different as you can get a handle on actual declared type. You can then use java.lang.Class.isPrimitive() as expected and the type will be byte.class.

public class PrimitiveMadness {
    static byte bytePrimitiveField;
    static Byte byteWrapperField;

    public static void main(String[] args) throws Exception {
        System.out.println("Field type  =     " + PrimitiveMadness.class.getDeclaredField("bytePrimitiveField").getType());
        System.out.println("Is a byte   =     " + (PrimitiveMadness.class.getDeclaredField("bytePrimitiveField").getType() == byte.class));
        System.out.println("Is a primitive? = " + PrimitiveMadness.class.getDeclaredField("bytePrimitiveField").getType().isPrimitive());
        System.out.println("Wrapper field   = " + PrimitiveMadness.class.getDeclaredField("byteWrapperField").getType());
    }

}

这篇关于有没有办法检查instanceof基元变量java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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