Created
March 20, 2011 01:16
-
-
Save ryoasai/877976 to your computer and use it in GitHub Desktop.
Array reflection sample.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Array; | |
public class ArrayReflection { | |
public static void main(String[] args) throws Exception { | |
Class<String> clazz = String.class; | |
Class<?> arrayClass = Array.newInstance(clazz, 0).getClass(); | |
System.out.println(arrayClass.getName()); | |
Class<String[]> arrayClass2 = toArrayClass(clazz); | |
System.out.println(arrayClass == arrayClass2); | |
assert (arrayClass == arrayClass2); | |
} | |
public static <T> Class<T[]> toArrayClass(Class<T> clazz) { | |
try { | |
@SuppressWarnings("unchecked") | |
Class<T[]> result = (Class<T[]>)Class.forName("[L" + clazz.getName() + ";"); | |
return result; | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
throw new RuntimeException(e); | |
// Should not happen. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment