检查 java.lang.reflect.Field 类型是否为字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13008746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:08:32  来源:igfitidea点击:

Check if java.lang.reflect.Field type is a byte array

javareflection

提问by Paulius Matulionis

I don't do much of reflection so this question might be obvious. For e.g. I have a class:

我没有做太多反思,所以这个问题可能很明显。例如,我有一堂课:

public class Document {

    private String someStr;    

    private byte[] contents;  

    //Getters and setters

}

I am trying to check if the field contentsis an instance of byte array. What I tried:

我正在尝试检查该字段contents是否是字节数组的实例。我试过的:

Class clazz = Document.class;
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
    if (field.getType().isArray()) {
        Object array = field.getType();
        System.out.println(array);
    }
}

The output of this code is: class [B. I see that byte array is found, but if I do:

这段代码的输出是:class [B。我看到找到了字节数组,但如果我这样做:

if (array instanceof byte[]) {...}

This condition is never true. Why is that? And how to check if the object contains fields which are of type of byte[]?

这种情况是从来没有的true。这是为什么?以及如何检查对象是否包含类型为 的字段byte[]

回答by axtavt

array instanceof byte[]checks whether arrayis an object of type byte[]. But in your case arrayis not a byte[], it's an object of type Classthat represents byte[].

array instanceof byte[]检查是否array是类型的对象byte[]。但在你的情况下array不是 a byte[],它是一个Class代表byte[].

You can access a Classthat represents some type Tas T.class, therefore you need the following check:

您可以访问Class表示某种类型TT.class,因此,你需要以下检查:

if (array == byte[].class) { ... }

回答by Peter Lawrey

if the array is a class only instanceof Classwill be true..

如果数组是一个类只会instanceof Class是真的..

If you want to check the type of a field you can use

如果要检查字段的类型,可以使用

if(field.getType() == byte[].class)

回答by Jesper

Try this:

试试这个:

Class<?> cls = field.getType();
if (cls.isAssignableFrom(byte[].class)) {
    System.out.println("It's a byte array");
}

回答by Brian Agnew

See this useful tutorial from Oracle

查看来自 Oracle 的这个有用的教程

Array types may be identified by invoking Class.isArray()

数组类型可以通过调用 Class.isArray() 来识别

回答by assylias

If you try:

如果你试试:

Class<?> array = field.getType();
System.out.println(array.getCanonicalName());

it prints byte[]. But @axtavt's answer is better.

它打印byte[]。但@axtavt 的回答更好。