繁体   English   中英

如何确定Java中的字段是否为char [](char数组)类型?

[英]How to determine if a field is of type char[] (char array) in Java?

我通过反射动态地实例化对象,方法是将字段名称与Map中的同名键进行匹配。 其中一个字段是字符数组(char []):

private char[] traceResponseStatus;

在plinko迭代器中,我有目标类的类型代码,例如。

Collection<Field> fields = EventUtil.getAllFields(MyClass.getClass()).values();
for (Field field : fields)
{
Object value = aMap.get(field.getName());
...
    else if (Date.class.equals(fieldClass))
    {

例如, fieldClass将是Date

class MyClass
{
    private Date foo;

如果fieldClass类型是char [],那么测试表达式是什么?

您需要使用的代码是:

(variableName instanceof char[])

instanceof是一个运算符,它返回一个布尔值,指示左边的对象是否是右边类型的实例,即对于除null之外的所有内容,应该为variable instanceof Object返回true,在您的情况下,它将确定您的字段是否为char数组。

你在找

else if (traceResponseStatus instanceof char[])

@ bdean20处于正确的轨道上,但是具体的(现在很明显的)解决方案是:

if(char[].class.equals(field.getType()))

测试代码:

import java.lang.reflect.Field;


public class Foo {

    char[] myChar;

    public static void main(String[] args) {
        for (Field field : Foo.class.getDeclaredFields()) {
            System.out.format("Name: %s%n", field.getName());
            System.out.format("\tType: %s%n", field.getType());
            System.out.format("\tGenericType: %s%n", field.getGenericType());
            if(char[].class.equals(field.getClass()))
            {
                System.out.println("Class match");
            }
            if(char[].class.equals(field.getType()))
            {
                System.out.println("Type match");
            }
        }
    }
}

输出:

Name: myChar
    Type: class [C
    GenericType: class [C
Type match

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM