code

반사를 사용하지 않고 객체가 배열인지 확인하는 방법은 무엇입니까?

codestyles 2020. 9. 4. 07:28
반응형

반사를 사용하지 않고 객체가 배열인지 확인하는 방법은 무엇입니까?


리플렉션을 사용하지 않고 객체가 배열인지 Java에서 어떻게 볼 수 있습니까? 리플렉션을 사용하지 않고 모든 항목을 어떻게 반복 할 수 있습니까?

Google GWT를 사용하므로 리플렉션을 사용할 수 없습니다.

반성을 사용하지 않고 다음 메서드를 구현하고 싶습니다.

private boolean isArray(final Object obj) {
  //??..
}

private String toString(final Object arrayObject) {
  //??..
}

BTW : 비 GWT 환경에서 사용할 수 있도록 JavaScript를 사용하고 싶지도 않습니다.


당신이 사용할 수있는 Class.isArray()

public static boolean isArray(Object obj)
{
    return obj!=null && obj.getClass().isArray();
}

이것은 객체 및 기본 유형 배열 모두에서 작동합니다.

toString의 경우 Arrays.toString. 배열 유형을 확인하고 적절한 toString메서드를 호출해야합니다 .


사용할 수 있습니다 instanceof.

JLS 15.20.2 유형 비교 연산자 instanceof

 RelationalExpression:
    RelationalExpression instanceof ReferenceType

런타임에 instanceof연산자 의 결과 trueRelationalExpression 의 값 이 아닌 경우 null이고 참조 는를 발생시키지 않고 ReferenceType 으로 캐스팅 될 수 있습니다 ClassCastException. 그렇지 않으면 결과는 false입니다.

즉, 다음과 같이 할 수 있습니다.

Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"        

당신은 객체가이 있는지 확인해야 할 것 instanceof boolean[], byte[], short[], char[], int[], long[], float[], double[], 또는 Object[], 당신은 모든 배열 유형을 감지합니다.

또한 an int[][]instanceof Object[]이므로 중첩 배열을 처리하려는 방법에 따라 복잡해질 수 있습니다.

를 들어 toString, java.util.ArraystoString(int[])당신이 사용할 수있는 다른 오버로드. 또한이 deepToString(Object[])중첩 배열을 위해.

public String toString(Object arr) {
   if (arr instanceof int[]) {
      return Arrays.toString((int[]) arr);
   } else //...
}

그것은 매우 반복적 일 것입니다 (그러나 java.util.Arrays매우 반복적 일 것입니다 ). 그러나 그것은 배열이있는 Java에서하는 방식입니다.

또한보십시오


다음 코드를 사용하여 배열의 각 요소에 개별적으로 액세스 할 수 있습니다.

Object o=...;
if ( o.getClass().isArray() ) {
    for(int i=0; i<Array.getLength(o); i++){
        System.out.println(Array.get(o, i));
    }
}

모든 배열에서 작동하므로 기본 배열의 종류를 알 필요가 없습니다.


기본 유형의 배열간에 또는 기본 유형의 배열과 참조 유형의 배열 간에는 하위 유형 관계가 없습니다. JLS 4.10.3을 참조하십시오 .

따라서 다음은가 모든 종류obj 의 배열 인지 확인하는 테스트로 올바르지 않습니다 .

// INCORRECT!
public boolean isArray(final Object obj) {
    return obj instanceof Object[];
}

Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)

I use Google GWT so I am not allowed to use reflection :(

The best solution (to the isArray array part of the question) depends on what counts as "using reflection".

  • In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.

  • Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.

    public boolean isArray(final Object obj) {
        return obj instanceof Object[] || obj instanceof boolean[] ||
           obj instanceof byte[] || obj instanceof short[] ||
           obj instanceof char[] || obj instanceof int[] ||
           obj instanceof long[] || obj instanceof float[] ||
           obj instanceof double[];
    }
    
  • You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.

    public boolean isArray(final Object obj) {
        return obj.getClass().toString().charAt(0) == '[';
    }
    

1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.


You can create a utility class to check if the class represents any Collection, Map or Array

  public static boolean isCollection(Class<?> rawPropertyType) {
        return Collection.class.isAssignableFrom(rawPropertyType) || 
               Map.class.isAssignableFrom(rawPropertyType) || 
               rawPropertyType.isArray();
 }

참고URL : https://stackoverflow.com/questions/2725533/how-to-see-if-an-object-is-an-array-without-using-reflection

반응형