0

I have try following code, but it return false.

package ro.idea.ex;

import java.lang.reflect.Array;
import java.util.Collection;

/**
 * Created by roroco on 10/28/14.
 */
public class Ex {
    public <T> boolean canWorkInForLoop(T o) {
        return o instanceof Collection || o instanceof Iterable || o instanceof Array;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2};
        Object r = new Ex().canWorkInForLoop(arr);
        System.out.println("r:" + r + "\t\t" + new Exception().getStackTrace()[0].getFileName() + ":" + new Exception().getStackTrace()[0].getLineNumber());
    }
}

my question is:

How to determine all obj which can be used in for loop, like new int[], instance of ArrayList and other obj?

roroco
  • 439
  • 1
  • 6
  • 14

1 Answers1

1

int[] is not an instance of Array. use o.getClass().isArray() instead

more information can be found in the answer to this question

Also, the Collection check is redundant since it extends Iterable, the for each construct is applicable to Iterable's or arrays.

as explained in the comments, java.lang.reflect.Array is a utility class for creating/accessing arrays. It is not a base class for arrays.
arrays of objects extends Object[], while primitive arrays extend Object according to this answer

Community
  • 1
  • 1
yurib
  • 8,043
  • 3
  • 30
  • 55
  • i have some confused about o.getClass().isArray() but o is not instance of Array, why java is designed like that? – roroco Oct 28 '14 at 15:42
  • @user3370849 `java.lang.reflect.Array` is a utility class for introspection. Arrays in Java do not inherit from it. – Radiodef Oct 28 '14 at 15:44
  • @user3370849 Array is a class with static methods for handling arrays. object arrays extend Object[] and primitive arrays, i'm not sure what they extend if anything... – yurib Oct 28 '14 at 15:44
  • Look at the [javadoc for `java.lang.reflect.Array`](http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html) for more details - you'll see it's a utility class (all methods are static), not a class you are meant to instantiate. The name of the class is a tad confusing, I'll warrant, but the package name tells the story, that this is for reflection. It's not in `java.util`, after all. – dcsohl Oct 28 '14 at 15:47