简体   繁体   中英

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. One of the fields is a character array (char[]):

private char[] traceResponseStatus;

In the plinko iterator I have code for the types on the target class, eg.

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

class MyClass
{
    private Date foo;

What's the expression to test if the fieldClass type is a 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.

你在找

else if (traceResponseStatus instanceof char[])

@bdean20 was on right track with the dupe suggestion, but the specific (and now obvious) solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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