简体   繁体   English

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

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

I'm dynamically instantiating an object through reflection, by matching fields names to like-named keys in a Map. 我通过反射动态地实例化对象,方法是将字段名称与Map中的同名键进行匹配。 One of the fields is a character array (char[]): 其中一个字段是字符数组(char []):

private char[] traceResponseStatus;

In the plinko iterator I have code for the types on the target class, eg. 在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))
    {

where the fieldClass , for example, would be Date 例如, fieldClass将是Date

class MyClass
{
    private Date foo;

What's the expression to test if the fieldClass type is a char[]? 如果fieldClass类型是char [],那么测试表达式是什么?

The code you need to use is: 您需要使用的代码是:

(variableName instanceof char[])

instanceof is an operator that returns a boolean indicating whether the object on the left is an instance of the type on the right ie this should return true for variable instanceof Object for everything except null, and in your case it will determine if your field is a char array. instanceof是一个运算符,它返回一个布尔值,指示左边的对象是否是右边类型的实例,即对于除null之外的所有内容,应该为variable instanceof Object返回true,在您的情况下,它将确定您的字段是否为char数组。

你在找

else if (traceResponseStatus instanceof char[])

@bdean20 was on right track with the dupe suggestion, but the specific (and now obvious) solution: @ bdean20处于正确的轨道上,但是具体的(现在很明显的)解决方案是:

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

Test code: 测试代码:

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");
            }
        }
    }
}

Output: 输出:

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

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

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