2

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[]?

Todd Chambery
  • 3,195
  • 4
  • 19
  • 27

3 Answers3

3

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 i.e. 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.

bdean20
  • 822
  • 8
  • 14
  • I actually need a test for the Class of the field on the thing I'm populating (admittedly, my question was perfectly unclear). I've updated the question to hopefully clarify. – Todd Chambery Jun 01 '14 at 13:09
  • 1
    The question now appears to be a duplicate of this: http://stackoverflow.com/questions/1868333/how-can-i-determine-the-type-of-a-generic-field-in-java – bdean20 Jun 01 '14 at 23:22
2

@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
Todd Chambery
  • 3,195
  • 4
  • 19
  • 27
1

You are looking for

else if (traceResponseStatus instanceof char[])
TheMP
  • 8,257
  • 9
  • 44
  • 73