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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
The question now appears to be a duplicate of this: stackoverflow.com/questions/1868333/…
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

Comments

1

You are looking for

else if (traceResponseStatus instanceof char[])

1 Comment

I botched the question (see comment to @bdean20 above).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.